{"version":3,"sources":["../src/storage/index.ts","../src/integration-orm.ts","../src/docs/index.ts","../src/docs/handler.ts","../src/client/document-head.ts","../src/markdown.ts","../src/routing/specificity.ts","../src/server-http.ts","../src/docs/fonts.ts","../src/docs/last-modified.ts","../src/docs/search-client.ts","../src/docs/social-image.ts","../src/docs/adapter.ts","../src/docs/api.ts","../src/integration-api.ts","../src/utils/decode.ts","../src/request-context.ts","../src/integrations.ts","../src/workflows.ts","../src/env.ts","../src/server-action-security.ts","../src/cache-invalidation.ts","../src/layers.ts","../src/config.ts","../src/i18n/config.ts","../src/auth-config.ts","../src/renderer.ts","../src/docs/framework-detect.ts"],"sourcesContent":["import { createStorage, prefixStorage, builtinDrivers, type BuiltinDriverName } from \"unstorage\";\nimport type { Driver, Storage, TransactionOptions } from \"unstorage\";\nimport type { Database } from \"db0\";\nimport memoryDriver from \"unstorage/drivers/memory\";\nimport type {\n  FarmStorageClient,\n  FarmStorageClientConfig,\n  FarmStorageConfigObject,\n  FarmStorageLocalDriverConfig,\n  FarmStorageDatabaseConfig,\n  FarmStorageDatabaseDriverMap,\n  FarmStorageDatabaseDriverName,\n  FarmStorageRuntimeClient,\n  FarmStorageMountConfig,\n  FarmStorageMounts,\n  FarmStorageUserConfig,\n} from \"./types\";\n\nexport type {\n  FarmStorageBuiltinDriverConfig,\n  FarmStorageClient,\n  FarmStorageClientConfig,\n  FarmStorageConfigObject,\n  FarmStorageCustomDriverConfig,\n  FarmStorageDatabaseConfig,\n  FarmStorageDatabaseDriverName,\n  FarmStorageLocalDriverConfig,\n  FarmStorageRuntimeClient,\n  FarmStorageMountConfig,\n  FarmStorageMounts,\n  FarmStorageUserConfig,\n} from \"./types\";\nexport type {\n  BuiltinDriverName,\n  BuiltinDriverOptions,\n  Driver,\n  Storage,\n  StorageMeta,\n  StorageValue,\n  TransactionOptions,\n} from \"unstorage\";\nexport type { ConnectorName, ConnectorOptions, Database } from \"db0\";\n\ntype DriverFactoryModule = {\n  default: (options?: Record<string, any>) => Driver;\n};\n\ntype DriverResolver = () => Driver | Promise<Driver>;\ntype ModuleLoader = <T = any>(specifier: string) => Promise<T>;\n\nconst loadModule: ModuleLoader = (specifier) => import(/* @vite-ignore */ specifier);\n\nconst DATABASE_CONNECTORS: {\n  [K in FarmStorageDatabaseDriverName]: {\n    connector: FarmStorageDatabaseDriverMap[K];\n    load: () => Promise<{ default: (options?: any) => any }>;\n  };\n} = {\n  sqlite: {\n    connector: \"node-sqlite\",\n    load: () => loadModule(\"db0/connectors/node-sqlite\"),\n  },\n  \"node-sqlite\": {\n    connector: \"node-sqlite\",\n    load: () => loadModule(\"db0/connectors/node-sqlite\"),\n  },\n  sqlite3: {\n    connector: \"sqlite3\",\n    load: () => loadModule(\"db0/connectors/sqlite3\"),\n  },\n  \"better-sqlite3\": {\n    connector: \"better-sqlite3\",\n    load: () => loadModule(\"db0/connectors/better-sqlite3\"),\n  },\n  postgres: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  postgresql: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  pg: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  mysql: {\n    connector: \"mysql2\",\n    load: () => loadModule(\"db0/connectors/mysql2\"),\n  },\n  mysql2: {\n    connector: \"mysql2\",\n    load: () => loadModule(\"db0/connectors/mysql2\"),\n  },\n  pglite: {\n    connector: \"pglite\",\n    load: () => loadModule(\"db0/connectors/pglite\"),\n  },\n  planetscale: {\n    connector: \"planetscale\",\n    load: () => loadModule(\"db0/connectors/planetscale\"),\n  },\n  libsql: {\n    connector: \"libsql\",\n    load: () => loadModule(\"db0/connectors/libsql/node\"),\n  },\n  \"libsql-node\": {\n    connector: \"libsql-node\",\n    load: () => loadModule(\"db0/connectors/libsql/node\"),\n  },\n  \"libsql-http\": {\n    connector: \"libsql-http\",\n    load: () => loadModule(\"db0/connectors/libsql/http\"),\n  },\n};\n\nfunction createMemoryStorage(): Storage {\n  return createStorage({\n    driver: memoryDriver(),\n  });\n}\n\nconst GLOBAL_STORAGE_KEY = Symbol.for(\"farmjs.storage.global\");\n\nfunction readGlobalStorage(): Storage | undefined {\n  return (globalThis as unknown as Record<PropertyKey, Storage | undefined>)[GLOBAL_STORAGE_KEY];\n}\n\nfunction writeGlobalStorage(storage: Storage): Storage {\n  (globalThis as unknown as Record<PropertyKey, Storage | undefined>)[GLOBAL_STORAGE_KEY] = storage;\n  return storage;\n}\n\nfunction getActiveGlobalStorage(): Storage {\n  const existing = readGlobalStorage();\n  if (existing) {\n    return existing;\n  }\n  return writeGlobalStorage(createMemoryStorage());\n}\n\nlet globalStorage = getActiveGlobalStorage();\n\nfunction normalizeMountKey(base?: string): string {\n  return (base || \"\")\n    .trim()\n    .replace(/^[:/\\\\]+|[:/\\\\]+$/g, \"\")\n    .replace(/[\\\\/]+/g, \":\");\n}\n\nfunction isDriverInstance(value: unknown): value is Driver {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as Driver).getItem === \"function\" &&\n    typeof (value as Driver).getKeys === \"function\"\n  );\n}\n\nfunction isStorageInstance(value: unknown): value is Storage {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as Storage).mount === \"function\" &&\n    typeof (value as Storage).getMount === \"function\"\n  );\n}\n\nfunction isStorageClient(value: unknown): value is FarmStorageClient {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (value as FarmStorageClient).kind === \"farm-storage-client\" &&\n    typeof (value as FarmStorageClient).resolveDriver === \"function\" &&\n    typeof (value as FarmStorageClient).createStorage === \"function\"\n  );\n}\n\nfunction isDatabaseDriverName(name: string): name is FarmStorageDatabaseDriverName {\n  return name in DATABASE_CONNECTORS;\n}\n\nfunction extractDriverOptions(config: FarmStorageClientConfig): Record<string, any> | undefined {\n  const source = config as Record<string, any>;\n  const {\n    client: _client,\n    driver: _driver,\n    mounts: _mounts,\n    options,\n    tableName: _tableName,\n    ...inlineOptions\n  } = source;\n  const hasInlineOptions = Object.keys(inlineOptions).length > 0;\n\n  if (options && typeof options === \"object\" && !Array.isArray(options)) {\n    return hasInlineOptions ? { ...inlineOptions, ...options } : options;\n  }\n\n  if (hasInlineOptions) {\n    return inlineOptions;\n  }\n\n  return options;\n}\n\nasync function loadBuiltinDriver(\n  name: BuiltinDriverName,\n  options?: Record<string, any>,\n): Promise<Driver> {\n  const modulePath = builtinDrivers[name];\n\n  if (!modulePath) {\n    throw new Error(`Unsupported storage driver \"${name}\".`);\n  }\n\n  const module = (await loadModule(modulePath)) as DriverFactoryModule;\n  return module.default(options);\n}\n\nasync function loadDatabaseDriver(config: FarmStorageDatabaseConfig): Promise<Driver> {\n  const connectorEntry = DATABASE_CONNECTORS[config.driver as FarmStorageDatabaseDriverName];\n  const [{ createDatabase }, connectorModule, db0DriverModule] = await Promise.all([\n    loadModule<typeof import(\"db0\")>(\"db0\"),\n    connectorEntry.load(),\n    loadModule<typeof import(\"unstorage/drivers/db0\")>(\"unstorage/drivers/db0\"),\n  ]);\n\n  const database = createDatabase(connectorModule.default(extractDriverOptions(config) || {}));\n  const driver = db0DriverModule.default({\n    database,\n    tableName: config.tableName,\n  });\n\n  // The db0 driver has no dispose, so this connection is Farm's to close. Databases\n  // handed to `databaseStorage` stay owned by the caller and are left open.\n  return {\n    ...driver,\n    async dispose() {\n      await driver.dispose?.();\n      await database.dispose();\n    },\n  };\n}\n\nasync function resolveDriver(config?: FarmStorageMountConfig): Promise<Driver> {\n  if (config && isStorageClient(config)) {\n    return config.resolveDriver();\n  }\n\n  const driverInput = config?.driver ?? \"memory\";\n\n  if (typeof driverInput === \"function\") {\n    return await driverInput();\n  }\n\n  if (isDriverInstance(driverInput)) {\n    return driverInput;\n  }\n\n  if (isDatabaseDriverName(driverInput)) {\n    return loadDatabaseDriver(config as FarmStorageDatabaseConfig);\n  }\n\n  if (driverInput === \"local\") {\n    return loadBuiltinDriver(\"fs-lite\", extractDriverOptions(config as FarmStorageMountConfig));\n  }\n\n  return loadBuiltinDriver(\n    driverInput as BuiltinDriverName,\n    extractDriverOptions(config as FarmStorageClientConfig),\n  );\n}\n\nfunction createStorageClientFromResolver(resolveDriver: DriverResolver): FarmStorageClient {\n  let driverPromise: Promise<Driver> | undefined;\n  let storagePromise: Promise<Storage> | undefined;\n\n  const ensureDriver = () => {\n    if (driverPromise) return driverPromise;\n\n    const pending = Promise.resolve().then(resolveDriver);\n    driverPromise = pending;\n    void pending.catch(() => {\n      if (driverPromise === pending) {\n        driverPromise = undefined;\n        storagePromise = undefined;\n      }\n    });\n    return pending;\n  };\n\n  const ensureStorage = () => {\n    if (storagePromise) return storagePromise;\n\n    const pending = ensureDriver().then((driver) =>\n      createStorage({\n        driver,\n      }),\n    );\n    storagePromise = pending;\n    void pending.catch(() => {\n      if (storagePromise === pending) storagePromise = undefined;\n    });\n    return pending;\n  };\n\n  const target = {\n    kind: \"farm-storage-client\" as const,\n    ready: ensureStorage,\n    createStorage: ensureStorage,\n    resolveDriver: ensureDriver,\n  };\n\n  return new Proxy(target as FarmStorageClient, {\n    get(currentTarget, prop, receiver) {\n      if (prop === \"then\") {\n        return undefined;\n      }\n\n      if (Reflect.has(currentTarget, prop)) {\n        return Reflect.get(currentTarget, prop, receiver);\n      }\n\n      return (...args: any[]) =>\n        ensureStorage().then(async (storage) => {\n          const member = Reflect.get(storage as object, prop);\n\n          if (typeof member !== \"function\") {\n            return member;\n          }\n\n          const result = Reflect.apply(member, storage, args);\n\n          if (prop === \"dispose\") {\n            return Promise.resolve(result).finally(() => {\n              // Disposing the storage also disposed the driver, so drop both\n              // cached promises: a later call must re-run the driver factory\n              // instead of rebuilding storage over the dead driver.\n              storagePromise = undefined;\n              driverPromise = undefined;\n            });\n          }\n\n          return result;\n        });\n    },\n  });\n}\n\nexport function defineStorageClient(resolveDriver: DriverResolver): FarmStorageClient {\n  return createStorageClientFromResolver(resolveDriver);\n}\n\nexport function createStorageClient(config: FarmStorageClientConfig): FarmStorageClient {\n  return defineStorageClient(() => resolveDriver(config));\n}\n\nexport function driverStorage(\n  driver: Driver | (() => Driver | Promise<Driver>),\n): FarmStorageClient {\n  return defineStorageClient(() => (typeof driver === \"function\" ? driver() : driver));\n}\n\nexport function databaseStorage(\n  database: Database,\n  options: { tableName?: string } = {},\n): FarmStorageClient {\n  return defineStorageClient(async () => {\n    const db0DriverModule =\n      await loadModule<typeof import(\"unstorage/drivers/db0\")>(\"unstorage/drivers/db0\");\n    return db0DriverModule.default({\n      database,\n      tableName: options.tableName,\n    });\n  });\n}\n\nexport function memoryStorage(): FarmStorageClient {\n  return createStorageClient({ driver: \"memory\" });\n}\n\nexport function localStorage(options: Omit<FarmStorageLocalDriverConfig, \"driver\"> = {}) {\n  return createStorageClient({\n    driver: \"local\",\n    ...options,\n  });\n}\n\nexport function sqliteStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"sqlite\",\n    ...options,\n  });\n}\n\nexport function mysqlStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"mysql\",\n    ...options,\n  });\n}\n\nexport function mysql2Storage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return mysqlStorage(options);\n}\n\nexport function postgresStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"postgres\",\n    ...options,\n  });\n}\n\nexport function pgStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return postgresStorage(options);\n}\n\nexport function pgliteStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"pglite\",\n    ...options,\n  });\n}\n\nexport function planetscaleStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"planetscale\",\n    ...options,\n  });\n}\n\nexport function libsqlStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"libsql\",\n    ...options,\n  });\n}\n\nexport function redisStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"redis\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"redis\",\n    ...options,\n  });\n}\n\nexport function s3Storage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"s3\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"s3\",\n    ...options,\n  });\n}\n\nexport function mongodbStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"mongodb\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"mongodb\",\n    ...options,\n  });\n}\n\nexport function upstashStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"upstash\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"upstash\",\n    ...options,\n  });\n}\n\nexport function netlifyBlobsStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"netlify-blobs\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"netlify-blobs\",\n    ...options,\n  });\n}\n\nexport function vercelKVStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"vercel-kv\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"vercel-kv\",\n    ...options,\n  });\n}\n\nexport function vercelBlobStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"vercel-blob\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"vercel-blob\",\n    ...options,\n  });\n}\n\nasync function mountNamespaces(storage: Storage, mounts?: FarmStorageMounts): Promise<void> {\n  if (!mounts) {\n    return;\n  }\n\n  for (const [base, config] of Object.entries(mounts)) {\n    storage.mount(normalizeMountKey(base), await resolveDriver(config));\n  }\n}\n\nexport async function createFarmStorage(config: FarmStorageUserConfig = {}): Promise<Storage> {\n  if (isStorageInstance(config)) {\n    return config;\n  }\n\n  if (isStorageClient(config)) {\n    return config.createStorage();\n  }\n\n  const rootConfig = isStorageClient(config.client) ? config.client : config;\n  const storage = createStorage({\n    driver: await resolveDriver(rootConfig),\n  });\n\n  try {\n    await mountNamespaces(storage, config.mounts);\n  } catch (error) {\n    await storage.dispose().catch(() => {});\n    throw error;\n  }\n  return storage;\n}\n\nexport async function resolveStorageRuntimeClient(\n  config: FarmStorageUserConfig | undefined,\n): Promise<unknown | undefined> {\n  if (!config || isStorageInstance(config) || isStorageClient(config)) {\n    return undefined;\n  }\n\n  const client = config.client;\n  if (!client || isStorageInstance(client) || isStorageClient(client)) {\n    return undefined;\n  }\n\n  return typeof client === \"function\" ? await client() : client;\n}\n\nexport async function initStorage(config: FarmStorageUserConfig = {}): Promise<Storage> {\n  globalStorage = getActiveGlobalStorage();\n  const nextStorage = await createFarmStorage(config);\n  const previousStorage = globalStorage;\n  globalStorage = writeGlobalStorage(nextStorage);\n\n  if (previousStorage !== nextStorage) {\n    await previousStorage.dispose().catch(() => {});\n  }\n\n  return globalStorage;\n}\n\nexport function getStorage(namespace?: string): Storage {\n  globalStorage = getActiveGlobalStorage();\n  const base = normalizeMountKey(namespace);\n  if (!base) {\n    return globalStorage;\n  }\n\n  const namespaced = prefixStorage(globalStorage, base);\n  // prefixStorage re-prefixes the key methods, but copies dispose/watch/getMount(s)\n  // straight from the parent, so on a namespaced view they operate on the whole\n  // global store: dispose() tears down every namespace, watch() sees (and leaks\n  // the raw keys of) every other namespace's writes, getMounts() lists them all.\n  // Scope those too, so a handle handed out as \"namespace X\" stays confined to X.\n  const store = globalStorage;\n  const prefix = `${base}:`;\n  const stripPrefix = (key: string) => (key.startsWith(prefix) ? key.slice(prefix.length) : key);\n  const viewUnwatchers = new Set<Awaited<ReturnType<Storage[\"watch\"]>>>();\n  const releaseViewWatchers = async () => {\n    const current = [...viewUnwatchers];\n    viewUnwatchers.clear();\n    await Promise.all(current.map((unwatch) => unwatch()));\n  };\n\n  return {\n    ...namespaced,\n    // Scope the wipe to the namespace instead of the whole storage, and keep\n    // the caller's base so `clear(\"sessions\")` cannot take unrelated keys with\n    // it. Dropping the argument silently widens a targeted clear into a\n    // namespace-wide delete.\n    async clear(base?: string, opts?: TransactionOptions) {\n      const keys = await namespaced.getKeys(base);\n      await Promise.all(keys.map((key) => namespaced.removeItem(key, opts)));\n    },\n    async watch(callback) {\n      const unwatch = await store.watch((event, key) => {\n        if (key.startsWith(prefix)) callback(event, stripPrefix(key));\n      });\n      viewUnwatchers.add(unwatch);\n      return async () => {\n        viewUnwatchers.delete(unwatch);\n        await unwatch();\n      };\n    },\n    async unwatch() {\n      await releaseViewWatchers();\n    },\n    async dispose() {\n      // A namespaced view shares the global store's lifecycle and owns no\n      // drivers, so disposing it must not tear down the global store (that is\n      // what disposeStorage is for). Release only this view's watchers.\n      await releaseViewWatchers();\n    },\n    getMount(key = \"\") {\n      return store.getMount(prefix + key);\n    },\n    getMounts(base = \"\", options) {\n      return store\n        .getMounts(prefix + base, options)\n        .map((mount) => ({ ...mount, base: stripPrefix(mount.base) }));\n    },\n  } as Storage;\n}\n\nexport async function disposeStorage(): Promise<void> {\n  globalStorage = getActiveGlobalStorage();\n  const previousStorage = globalStorage;\n  globalStorage = writeGlobalStorage(createMemoryStorage());\n  await previousStorage.dispose().catch(() => {});\n}\n","import type {\n  AnyFieldBuilder,\n  AnyModelDefinition,\n  FieldBuilder,\n  JsonValue,\n  ModelDefinition,\n  OrmClient,\n  SchemaDefinition,\n  SchemaModels,\n} from \"@farming-labs/orm\";\nimport type {\n  FarmIntegrationSchema,\n  FarmIntegrationSchemaField,\n  FarmIntegrationSchemaModel,\n} from \"./integrations\";\nimport { resolveStorageRuntimeClient } from \"./storage\";\nimport type { FarmStorageUserConfig } from \"./storage/types\";\nimport type { FarmConfig } from \"./types\";\n\ntype RuntimeClientFactory<TClient> = () => TClient | Promise<TClient>;\n\nexport type FarmIntegrationOrmSchema = SchemaDefinition<Record<string, AnyModelDefinition>>;\n\nexport type FarmIntegrationOrmClient<TSchema extends FarmIntegrationOrmSchema> = OrmClient<TSchema>;\n\ntype FarmIntegrationOrmFieldKind<TField extends FarmIntegrationSchemaField> = TField[\"type\"] extends\n  | \"id\"\n  | \"uuid\"\n  ? \"id\"\n  : TField[\"type\"] extends \"text\"\n    ? \"string\"\n    : TField[\"type\"] extends \"number\"\n      ? \"decimal\"\n      : Extract<TField[\"type\"], \"string\" | \"boolean\" | \"integer\" | \"datetime\" | \"json\" | \"enum\">;\n\ntype FarmIntegrationOrmFieldNullable<TField extends FarmIntegrationSchemaField> = TField extends {\n  nullable: true;\n}\n  ? true\n  : TField extends { required: false }\n    ? true\n    : false;\n\ntype FarmIntegrationOrmEnumValue<TField extends FarmIntegrationSchemaField> = TField extends {\n  values: readonly (infer TValue extends string)[];\n}\n  ? TValue\n  : string;\n\ntype FarmIntegrationOrmFieldValue<TField extends FarmIntegrationSchemaField> =\n  TField[\"type\"] extends \"id\" | \"uuid\" | \"string\" | \"text\"\n    ? string\n    : TField[\"type\"] extends \"boolean\"\n      ? boolean\n      : TField[\"type\"] extends \"integer\"\n        ? number\n        : TField[\"type\"] extends \"number\"\n          ? string\n          : TField[\"type\"] extends \"datetime\"\n            ? Date\n            : TField[\"type\"] extends \"json\"\n              ? JsonValue\n              : TField[\"type\"] extends \"enum\"\n                ? FarmIntegrationOrmEnumValue<TField>\n                : never;\n\nexport type InferFarmIntegrationOrmField<TField extends FarmIntegrationSchemaField> = FieldBuilder<\n  FarmIntegrationOrmFieldKind<TField>,\n  FarmIntegrationOrmFieldNullable<TField>,\n  FarmIntegrationOrmFieldValue<TField>\n>;\n\nexport type InferFarmIntegrationOrmFields<TModel extends FarmIntegrationSchemaModel> = {\n  [TFieldKey in keyof TModel[\"fields\"] & string]: InferFarmIntegrationOrmField<\n    Extract<TModel[\"fields\"][TFieldKey], FarmIntegrationSchemaField>\n  >;\n};\n\nexport type InferFarmIntegrationOrmSchema<TSchema extends FarmIntegrationSchema> =\n  SchemaDefinition<{\n    [TModelKey in keyof TSchema[\"models\"] & string]: ModelDefinition<\n      InferFarmIntegrationOrmFields<\n        Extract<TSchema[\"models\"][TModelKey], FarmIntegrationSchemaModel>\n      >,\n      {}\n    >;\n  }>;\n\nexport type InferFarmIntegrationOrmClient<TSchema extends FarmIntegrationSchema | undefined> =\n  TSchema extends FarmIntegrationSchema ? OrmClient<InferFarmIntegrationOrmSchema<TSchema>> : never;\n\nexport interface CreateIntegrationOrmOptions<\n  TClient = unknown,\n  TSchema extends FarmIntegrationSchema = FarmIntegrationSchema,\n> {\n  schema: TSchema;\n  config?: Pick<FarmConfig, \"storage\">;\n  storage?: FarmStorageUserConfig;\n  client?: TClient | RuntimeClientFactory<TClient>;\n}\n\nexport async function createIntegrationOrm<\n  TClient = unknown,\n  TSchema extends FarmIntegrationSchema = FarmIntegrationSchema,\n>(\n  options: CreateIntegrationOrmOptions<TClient, TSchema>,\n): Promise<InferFarmIntegrationOrmClient<TSchema>> {\n  const [schema, client] = await Promise.all([\n    farmIntegrationSchemaToOrmSchema(options.schema),\n    resolveIntegrationOrmRuntimeClient(options),\n  ]);\n\n  if (!client) {\n    throw new Error(\n      \"Schema-backed integration storage requires a runtime client at farm.config storage.client.\",\n    );\n  }\n\n  const { createOrmFromRuntime } = await import(\"@farming-labs/orm-runtime\");\n  return createOrmFromRuntime({\n    schema,\n    client,\n  }) as Promise<InferFarmIntegrationOrmClient<TSchema>>;\n}\n\nexport async function resolveIntegrationOrmRuntimeClient<TClient = unknown>(\n  options: Omit<CreateIntegrationOrmOptions<TClient>, \"schema\">,\n): Promise<TClient | unknown | undefined> {\n  if (options.client !== undefined) {\n    return typeof options.client === \"function\"\n      ? await (options.client as RuntimeClientFactory<TClient>)()\n      : options.client;\n  }\n\n  return resolveStorageRuntimeClient(options.storage ?? options.config?.storage);\n}\n\nexport async function farmIntegrationSchemaToOrmSchema(\n  schema: FarmIntegrationSchema,\n): Promise<FarmIntegrationOrmSchema> {\n  const orm = await import(\"@farming-labs/orm\");\n  const models: Record<string, AnyModelDefinition> = {};\n\n  for (const [modelKey, modelSchema] of Object.entries(schema.models)) {\n    models[modelKey] = orm.model({\n      table: modelSchema.name ?? modelKey,\n      fields: createOrmModelFields(orm, modelSchema),\n      constraints: createOrmModelConstraints(modelSchema),\n      description: modelSchema.description,\n    }) as AnyModelDefinition;\n  }\n\n  return orm.defineSchema(models) as FarmIntegrationOrmSchema;\n}\n\nfunction createOrmModelFields(\n  orm: typeof import(\"@farming-labs/orm\"),\n  modelSchema: FarmIntegrationSchemaModel,\n): Record<string, AnyFieldBuilder> {\n  return Object.fromEntries(\n    Object.entries(modelSchema.fields).map(([fieldKey, fieldSchema]) => [\n      fieldKey,\n      createOrmField(orm, fieldKey, fieldSchema),\n    ]),\n  );\n}\n\nfunction createOrmField(\n  orm: typeof import(\"@farming-labs/orm\"),\n  fieldKey: string,\n  field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n  let builder = createOrmFieldBuilder(orm, fieldKey, field) as AnyFieldBuilder;\n\n  if (field.unique) {\n    builder = builder.unique();\n  }\n\n  if (field.nullable || field.required === false) {\n    builder = builder.nullable();\n  }\n\n  if (field.default !== undefined) {\n    builder =\n      field.type === \"datetime\" && field.default === \"now\"\n        ? builder.defaultNow()\n        : builder.default(field.default as never);\n  }\n\n  if (field.reference) {\n    builder = builder.references(`${field.reference.model}.${field.reference.field}`);\n  }\n\n  if (field.name && field.name !== fieldKey) {\n    builder = builder.map(field.name);\n  }\n\n  if (field.description) {\n    builder = builder.describe(field.description);\n  }\n\n  return builder;\n}\n\nfunction createOrmFieldBuilder(\n  orm: typeof import(\"@farming-labs/orm\"),\n  fieldKey: string,\n  field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n  switch (field.type) {\n    case \"id\":\n    case \"uuid\":\n      return orm.id();\n    case \"string\":\n    case \"text\":\n      return orm.string();\n    case \"boolean\":\n      return orm.boolean();\n    case \"integer\":\n      return orm.integer();\n    case \"number\":\n      return orm.decimal();\n    case \"datetime\":\n      return orm.datetime();\n    case \"json\":\n      return orm.json();\n    case \"enum\": {\n      if (!field.values?.length) {\n        throw new Error(`Integration schema enum field \"${fieldKey}\" must define values.`);\n      }\n\n      return orm.enumeration(field.values as readonly [string, ...string[]]);\n    }\n    default:\n      throw new Error(\n        `Unsupported integration schema field type \"${field.type}\" for \"${fieldKey}\".`,\n      );\n  }\n}\n\nfunction createOrmModelConstraints(modelSchema: FarmIntegrationSchemaModel) {\n  const unique: Array<readonly [string, ...string[]]> = [];\n  const indexes: Array<readonly [string, ...string[]]> = [];\n\n  for (const constraint of modelSchema.constraints ?? []) {\n    if (!constraint.fields.length) {\n      continue;\n    }\n\n    const fields = constraint.fields as readonly [string, ...string[]];\n    if (constraint.type === \"unique\") {\n      unique.push(fields);\n    } else {\n      indexes.push(fields);\n    }\n  }\n\n  return {\n    unique,\n    indexes,\n  };\n}\n\nexport type IntegrationOrmModelNames<TSchema extends FarmIntegrationOrmSchema> =\n  keyof SchemaModels<TSchema> & string;\n","export {\n  createFarmDocsHandler,\n  discoverFarmDocsPages,\n  getFarmDocsDocumentNavigationMatchers,\n  getFarmDocsRouteTypeEntries,\n  isFarmDocsRequest,\n  loadFarmDocsPage,\n  resolveFarmDocsContentDir,\n} from \"./handler\";\nexport {\n  createFarmDocsAdapterHandler,\n  hasFarmDocsRuntimeAdapter,\n  type FarmDocsAdapterHandlerOptions,\n} from \"./adapter\";\nexport { createDocsAPI, createFarmDocsAPIHandler, isFarmDocsAPIRequest } from \"./api\";\nexport type { FarmDocsHandlerOptions, FarmDocsPage, LoadedFarmDocsPage } from \"./handler\";\nexport type {\n  FarmDocsAPIHandler,\n  FarmDocsAPIOptions,\n  FarmDocsAPIRouteHandlers,\n  FarmDocsCloudIntegration,\n  FarmDocsCloudRouteOptions,\n  FarmDocsCloudServer,\n} from \"./api\";\nexport type {\n  FarmDocsConfigInput,\n  FarmDocsNavigationConfig,\n  FarmDocsResolvedConfig,\n  FarmDocsSocialImageConfig,\n  FarmDocsSocialImageFonts,\n  FarmDocsSidebarItem,\n  FarmDocsUserConfig,\n} from \"./types\";\n","import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n  buildDocsAgentDiscoverySpec,\n  buildDocsSitemapManifest,\n  isDocsAgentDiscoveryRequest,\n  isDocsAgentsRequest,\n  isDocsSkillRequest,\n  renderDocsAgentsDocument,\n  renderDocsLlmsTxt,\n  renderDocsMarkdownDocument,\n  renderDocsRobotsTxt,\n  renderDocsSitemapMarkdown,\n  renderDocsSitemapXml,\n  renderDocsSkillDocument,\n  resolveDocsLlmsTxtFormat,\n  resolveDocsRobotsRequest,\n  resolveDocsSitemapRequest,\n  type DocsLlmsTxtPageInput,\n  type DocsMarkdownPage,\n  type DocsSitemapPageInput,\n} from \"@farming-labs/docs\";\nimport { marked, Renderer } from \"marked\";\nimport { highlight } from \"sugar-high\";\nimport { FARM_NAVIGATION_HEAD_SELECTOR } from \"../client/document-head\";\nimport { farmAcceptQuality } from \"../markdown\";\nimport type { FarmLayoutFonts } from \"../font\";\nimport { matchesFarmIfNoneMatch } from \"../server-http\";\nimport {\n  resolveFarmDocsFontAssets,\n  toFarmDocsPublicFontAssets,\n  type FarmDocsPublicFontAsset,\n} from \"./fonts\";\nimport { resolveFarmDocsPageLastModified } from \"./last-modified\";\nimport { generateFarmDocsSearchBootstrapRuntime, isFarmDocsSearchEnabled } from \"./search-client\";\nimport {\n  createFarmDocsSocialImageDescriptor,\n  getFarmDocsCustomSocialImage,\n  getFarmDocsSocialImageSlug,\n  isFarmDocsSocialImageEnabled,\n  renderFarmDocsSocialImageSvg,\n  renderFarmDocsSocialMetadata,\n} from \"./social-image\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\nexport interface FarmDocsHandlerOptions {\n  root: string;\n  srcDir?: string;\n  clientEntry?: string;\n  fontAssets?: readonly FarmDocsPublicFontAsset[];\n  /** Resolve semantic fonts from the layouts that apply to the requested docs route. */\n  resolveLayoutFonts?: (\n    pathname: string,\n  ) => FarmLayoutFonts | undefined | Promise<FarmLayoutFonts | undefined>;\n  /** Stylesheet containing the `@font-face` rules generated by Farm's font compiler. */\n  fontStylesheetHref?: string;\n  /** Application-owned global stylesheet, including the selected docs theme CSS import. */\n  globalStylesheetHref?: string;\n}\n\nexport interface FarmDocsPage {\n  slug: string;\n  title: string;\n  description?: string;\n  section?: string;\n  href: string;\n  sourcePath: string;\n  lastModified?: string;\n}\n\nexport interface LoadedFarmDocsPage extends FarmDocsPage {\n  body: string;\n  frontmatter: Record<string, string>;\n}\n\nconst DOCS_FILE_NAMES = [\"page.mdx\", \"page.md\", \"index.mdx\", \"index.md\"];\nconst DOCS_FILE_EXTENSIONS = [\".mdx\", \".md\"];\nconst FARM_DOCS_FALLBACK_FAVICON =\n  \"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' fill='black'/%3E%3Cpath d='M7 8h18v3H10v5h12v3H10v5H7z' fill='white'/%3E%3C/svg%3E\";\nconst FARM_DOCS_FAVICON_FILES = [\"favicon.svg\", \"favicon.ico\", \"favicon.png\"];\n\nfunction trimSlashes(value: string): string {\n  return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction normalizeEntry(entry: string | undefined): string {\n  if (!entry || entry === \"/\") return \"/\";\n  return `/${trimSlashes(entry)}`;\n}\n\nfunction decodeDocsPath(value: string): string {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    // Malformed percent-encoding in a request path must resolve to a\n    // non-matching slug (a 404), not throw out of the handler.\n    return value;\n  }\n}\n\nfunction normalizeSlug(value: string): string {\n  return trimSlashes(decodeDocsPath(value)).replace(/\\.(mdx?|markdown)$/i, \"\");\n}\n\nfunction resolveFarmDocsFavicon(\n  docs: FarmDocsResolvedConfig | undefined,\n  options: FarmDocsHandlerOptions,\n): string {\n  const configuredFavicon = docs?.config.favicon;\n  if (typeof configuredFavicon === \"string\" && configuredFavicon.trim()) {\n    return configuredFavicon.trim();\n  }\n\n  const publicDir = path.join(path.resolve(options.root), \"public\");\n\n  for (const fileName of FARM_DOCS_FAVICON_FILES) {\n    const faviconPath = path.join(publicDir, fileName);\n    if (existsSync(faviconPath) && statSync(faviconPath).isFile()) {\n      return `/${fileName}`;\n    }\n  }\n\n  return FARM_DOCS_FALLBACK_FAVICON;\n}\n\nfunction renderFarmDocsFaviconLink(faviconHref: string): string {\n  const normalizedHref = faviconHref.split(/[?#]/, 1)[0]?.toLowerCase() || \"\";\n  const type =\n    normalizedHref.endsWith(\".svg\") || faviconHref.startsWith(\"data:image/svg+xml\")\n      ? \"image/svg+xml\"\n      : normalizedHref.endsWith(\".png\")\n        ? \"image/png\"\n        : normalizedHref.endsWith(\".ico\")\n          ? \"image/x-icon\"\n          : undefined;\n  const metadata =\n    type === \"image/svg+xml\" ? ' sizes=\"any\" type=\"image/svg+xml\"' : type ? ` type=\"${type}\"` : \"\";\n\n  return `<link rel=\"icon\" href=\"${escapeAttribute(faviconHref)}\"${metadata}>`;\n}\n\nfunction renderFarmDocsBrandMark(): string {\n  return `<svg class=\"sidebar-brand-logo\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\">\n    <rect x=\"2\" y=\"2\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\"></rect>\n    <path d=\"M9.75 2h11.5c.41 0 .75.34.75.75v3.5c0 .41-.34.75-.75.75H9.75A.75.75 0 0 1 9 6.25v-3.5c0-.41.34-.75.75-.75Zm9.75 1.62a.38.38 0 0 0-.38.38v1c0 .21.17.38.38.38h.75c.21 0 .38-.17.38-.38V4a.38.38 0 0 0-.38-.38h-.75Z\" fill=\"currentColor\"></path>\n    <rect x=\"2\" y=\"9.5\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.64\"></rect>\n    <rect x=\"9\" y=\"9.5\" width=\"13\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.64\"></rect>\n    <rect x=\"2\" y=\"17\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.34\"></rect>\n    <rect x=\"9\" y=\"17\" width=\"7.5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.34\"></rect>\n  </svg>`;\n}\n\nfunction renderFarmDocsBrandTitle(navTitle: string): string {\n  const suffix = navTitle.match(/\\.js$/i)?.[0];\n\n  if (!suffix) {\n    return `<span class=\"sidebar-brand-title\">${escapeHtml(navTitle)}</span>`;\n  }\n\n  const productName = navTitle.slice(0, -suffix.length);\n  return `<span class=\"sidebar-brand-title\">${escapeHtml(productName)}<span class=\"sidebar-brand-suffix\">${escapeHtml(suffix)}</span></span>`;\n}\n\nfunction isSafeSegment(segment: string): boolean {\n  return segment !== \"..\" && !segment.includes(\"/\") && !segment.includes(\"\\\\\");\n}\n\nfunction resolveInside(root: string, target: string): string | null {\n  const resolvedRoot = path.resolve(root);\n  const resolvedTarget = path.resolve(target);\n  const relative = path.relative(resolvedRoot, resolvedTarget);\n  if (relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative))) {\n    return resolvedTarget;\n  }\n  return null;\n}\n\nfunction resolveExistingFileInside(root: string, target: string): string | null {\n  const safePath = resolveInside(root, target);\n  if (!safePath) return null;\n\n  try {\n    const realRoot = realpathSync(root);\n    const realTarget = realpathSync(safePath);\n    const containedTarget = resolveInside(realRoot, realTarget);\n    return containedTarget && statSync(containedTarget).isFile() ? containedTarget : null;\n  } catch {\n    return null;\n  }\n}\n\nexport function isFarmDocsRequest(docs: FarmDocsResolvedConfig | undefined, request: Request) {\n  if (!docs?.enabled) return false;\n  if (request.method !== \"GET\" && request.method !== \"HEAD\") return false;\n\n  const pathname = new URL(request.url).pathname;\n  const entry = normalizeEntry(docs.entry);\n  if (entry === \"/\") return true;\n\n  return pathname === entry || pathname === `${entry}.md` || pathname.startsWith(`${entry}/`);\n}\n\nexport function resolveFarmDocsContentDir(\n  docs: FarmDocsResolvedConfig,\n  options: FarmDocsHandlerOptions,\n): string {\n  const root = path.resolve(options.root);\n  const srcDir = options.srcDir || \"src\";\n  const configuredContentDir = docs.contentDir || docs.config.contentDir;\n\n  if (configuredContentDir) {\n    return path.isAbsolute(configuredContentDir)\n      ? configuredContentDir\n      : path.join(root, configuredContentDir);\n  }\n\n  const entryDir = docs.config.entry || trimSlashes(docs.entry) || \"docs\";\n  const appDocsDir = path.join(root, srcDir, \"app\", entryDir);\n  if (existsSync(appDocsDir)) return appDocsDir;\n\n  return path.join(root, entryDir);\n}\n\nexport function getFarmDocsRouteTypeEntries(docs: FarmDocsResolvedConfig | undefined): string[] {\n  if (!docs?.enabled) return [];\n  const entry = normalizeEntry(docs.entry);\n  if (entry === \"/\") return [\"/\", \"/[...docs]\"];\n  return [entry, `${entry}/[...docs]`];\n}\n\nexport function getFarmDocsDocumentNavigationMatchers(\n  docs: FarmDocsResolvedConfig | undefined,\n): string[] {\n  if (!docs?.enabled) return [];\n  const entry = normalizeEntry(docs.entry);\n  return [entry === \"/\" ? \"/(.*)\" : `${entry}(.*)`];\n}\n\nfunction getRequestSlug(docs: FarmDocsResolvedConfig, request: Request): string {\n  const pathname = new URL(request.url).pathname;\n  const entry = normalizeEntry(docs.entry);\n\n  if (entry === \"/\") return normalizeSlug(pathname);\n  if (pathname === entry || pathname === `${entry}.md`) return \"\";\n\n  return normalizeSlug(pathname.slice(entry.length));\n}\n\nfunction findDocsPageFile(contentDir: string, slug: string): string | null {\n  const segments = slug ? slug.split(\"/\").filter(Boolean) : [];\n  if (!segments.every(isSafeSegment)) return null;\n\n  const slugDir = path.join(contentDir, ...segments);\n  const candidates =\n    segments.length === 0\n      ? DOCS_FILE_NAMES.map((filename) => path.join(contentDir, filename))\n      : [\n          ...DOCS_FILE_NAMES.map((filename) => path.join(slugDir, filename)),\n          ...DOCS_FILE_EXTENSIONS.map((extension) => path.join(contentDir, `${slug}${extension}`)),\n        ];\n\n  for (const candidate of candidates) {\n    const safePath = resolveExistingFileInside(contentDir, candidate);\n    if (safePath) {\n      return safePath;\n    }\n  }\n\n  return null;\n}\n\nfunction parseFrontmatter(source: string): {\n  frontmatter: Record<string, string>;\n  body: string;\n} {\n  if (!source.startsWith(\"---\")) {\n    return { frontmatter: {}, body: source };\n  }\n\n  const endIndex = source.indexOf(\"\\n---\", 3);\n  if (endIndex === -1) return { frontmatter: {}, body: source };\n\n  const frontmatterSource = source.slice(3, endIndex).trim();\n  const body = source.slice(source.indexOf(\"\\n\", endIndex + 1) + 1);\n  const frontmatter: Record<string, string> = {};\n\n  for (const line of frontmatterSource.split(/\\r?\\n/)) {\n    const separator = line.indexOf(\":\");\n    if (separator === -1) continue;\n    const key = line.slice(0, separator).trim();\n    const value = line\n      .slice(separator + 1)\n      .trim()\n      .replace(/^[\"']|[\"']$/g, \"\");\n    if (key && value) frontmatter[key] = value;\n  }\n\n  return { frontmatter, body };\n}\n\nfunction titleFromSlug(slug: string): string {\n  const lastSegment = slug.split(\"/\").filter(Boolean).pop() || \"Docs\";\n  return lastSegment\n    .split(/[-_]/)\n    .filter(Boolean)\n    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n    .join(\" \");\n}\n\nfunction titleFromMarkdown(body: string, fallback: string): string {\n  const heading = body.match(/^#\\s+(.+)$/m)?.[1]?.trim();\n  return heading || fallback;\n}\n\nexport function loadFarmDocsPage(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n  slug: string,\n): LoadedFarmDocsPage | null {\n  const sourcePath = findDocsPageFile(contentDir, slug);\n  if (!sourcePath) return null;\n\n  const source = readFileSync(sourcePath, \"utf8\");\n  const { frontmatter, body } = parseFrontmatter(source);\n  const title = frontmatter.title || titleFromMarkdown(body, titleFromSlug(slug));\n  const href = createDocsHref(docs.entry, slug);\n\n  return {\n    slug,\n    title,\n    description: frontmatter.description,\n    section: frontmatter.section,\n    href,\n    sourcePath,\n    lastModified: resolveFarmDocsPageLastModified(contentDir, sourcePath, frontmatter),\n    frontmatter,\n    body,\n  };\n}\n\nfunction createDocsHref(entry: string, slug: string): string {\n  const normalizedEntry = normalizeEntry(entry);\n  const normalizedSlug = trimSlashes(slug);\n  if (normalizedEntry === \"/\") return normalizedSlug ? `/${normalizedSlug}` : \"/\";\n  return normalizedSlug ? `${normalizedEntry}/${normalizedSlug}` : normalizedEntry;\n}\n\nfunction pathToSlug(contentDir: string, filePath: string): string | null {\n  const relative = path.relative(contentDir, filePath).replace(/\\\\/g, \"/\");\n  if (relative.startsWith(\"..\")) return null;\n\n  const extension = path.extname(relative);\n  if (!DOCS_FILE_EXTENSIONS.includes(extension)) return null;\n\n  const withoutExtension = relative.slice(0, -extension.length);\n  if (withoutExtension === \"page\" || withoutExtension === \"index\") return \"\";\n  if (withoutExtension.endsWith(\"/page\") || withoutExtension.endsWith(\"/index\")) {\n    return withoutExtension.replace(/\\/(page|index)$/, \"\");\n  }\n  return withoutExtension;\n}\n\nfunction loadPage(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n  request: Request,\n): LoadedFarmDocsPage | null {\n  return loadFarmDocsPage(contentDir, docs, getRequestSlug(docs, request));\n}\n\nexport function discoverFarmDocsPages(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n): FarmDocsPage[] {\n  if (!existsSync(contentDir)) return [];\n\n  const pages: FarmDocsPage[] = [];\n  const visit = (dir: string) => {\n    for (const entry of readdirSync(dir, { withFileTypes: true })) {\n      if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n      const absolutePath = path.join(dir, entry.name);\n      if (entry.isDirectory()) {\n        visit(absolutePath);\n        continue;\n      }\n      if (!entry.isFile()) continue;\n\n      const slug = pathToSlug(contentDir, absolutePath);\n      if (slug === null) continue;\n\n      const source = readFileSync(absolutePath, \"utf8\");\n      const { frontmatter, body } = parseFrontmatter(source);\n      pages.push({\n        slug,\n        title: frontmatter.title || titleFromMarkdown(body, titleFromSlug(slug)),\n        description: frontmatter.description,\n        section: frontmatter.section,\n        href: createDocsHref(docs.entry, slug),\n        sourcePath: absolutePath,\n        lastModified: resolveFarmDocsPageLastModified(contentDir, absolutePath, frontmatter),\n      });\n    }\n  };\n\n  visit(contentDir);\n  return pages.sort((a, b) => a.href.localeCompare(b.href));\n}\n\nexport function toFarmDocsMarkdownPage(page: LoadedFarmDocsPage): DocsMarkdownPage {\n  const lastModified =\n    page.lastModified || page.frontmatter.lastModified || page.frontmatter.lastmod;\n\n  return {\n    slug: page.slug,\n    url: page.href,\n    title: page.title,\n    description: page.description,\n    lastModified,\n    lastmod: lastModified,\n    content: page.body,\n    rawContent: page.body,\n  };\n}\n\nfunction getDocsTitle(docs: FarmDocsResolvedConfig): string {\n  return typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n    ? String((docs.config.nav as { title?: unknown }).title || \"Documentation\")\n    : \"Documentation\";\n}\n\nfunction getDocsDescription(docs: FarmDocsResolvedConfig): string | undefined {\n  return docs.config.metadata?.description;\n}\n\nfunction getLoadedDocsPages(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n): LoadedFarmDocsPage[] {\n  return discoverFarmDocsPages(contentDir, docs)\n    .map((page) => loadFarmDocsPage(contentDir, docs, page.slug))\n    .filter((page): page is LoadedFarmDocsPage => Boolean(page));\n}\n\nfunction toDocsLlmsPage(page: LoadedFarmDocsPage): DocsLlmsTxtPageInput {\n  return toFarmDocsMarkdownPage(page);\n}\n\nfunction toDocsSitemapPage(page: LoadedFarmDocsPage): DocsSitemapPageInput {\n  return {\n    ...toFarmDocsMarkdownPage(page),\n    sourcePath: page.sourcePath,\n  };\n}\n\ntype CopyMarkdownActionConfig = {\n  format: \"markdown\" | \"text\";\n  includeTitle: boolean;\n  label: string;\n  copiedLabel: string;\n};\n\ntype LastUpdatedDisplayConfig = {\n  enabled: boolean;\n  label: string;\n  position: \"footer\" | \"below-title\";\n};\n\ntype ReadingTimeDisplayConfig = {\n  wordsPerMinute: number;\n  format: \"long\" | \"short\";\n  includeCode: boolean;\n};\n\nfunction resolvePageActionsConfig(docs: FarmDocsResolvedConfig): Record<string, unknown> {\n  return isObjectRecord(docs.config.pageActions) ? docs.config.pageActions : {};\n}\n\nfunction resolvePageActionsAlignment(docs: FarmDocsResolvedConfig): \"left\" | \"right\" {\n  return resolvePageActionsConfig(docs).alignment === \"right\" ? \"right\" : \"left\";\n}\n\nfunction resolveCopyMarkdownActionConfig(\n  docs: FarmDocsResolvedConfig,\n): CopyMarkdownActionConfig | null {\n  const raw = resolvePageActionsConfig(docs).copyMarkdown;\n  if (raw === undefined || raw === false) return null;\n\n  const options = isObjectRecord(raw) ? raw : {};\n  if (isObjectRecord(raw) && raw.enabled === false) return null;\n\n  return {\n    format: options.format === \"text\" ? \"text\" : \"markdown\",\n    includeTitle: options.includeTitle === true,\n    label: readString(options.label) ?? \"Copy page\",\n    copiedLabel: readString(options.copiedLabel) ?? \"Copied!\",\n  };\n}\n\nfunction resolveLastUpdatedDisplayConfig(docs: FarmDocsResolvedConfig): LastUpdatedDisplayConfig {\n  const raw = docs.config.lastUpdated;\n  const options = isObjectRecord(raw) ? raw : {};\n\n  return {\n    enabled: raw !== false && (!isObjectRecord(raw) || raw.enabled !== false),\n    label: typeof options.label === \"string\" ? options.label : \"Last updated\",\n    position: options.position === \"below-title\" ? \"below-title\" : \"footer\",\n  };\n}\n\nfunction formatLastModifiedDate(value: string | undefined): string | undefined {\n  if (!value) return undefined;\n\n  const date = new Date(value);\n  if (Number.isNaN(date.getTime())) return value;\n\n  return new Intl.DateTimeFormat(\"en\", {\n    day: \"numeric\",\n    month: \"long\",\n    year: \"numeric\",\n  }).format(date);\n}\n\nfunction renderLastUpdatedText(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n  position: \"footer\" | \"below-title\",\n): string {\n  const config = resolveLastUpdatedDisplayConfig(docs);\n  const formatted = formatLastModifiedDate(page.lastModified);\n  if (!config.enabled || config.position !== position || !formatted) return \"\";\n\n  const time = `<time datetime=\"${escapeAttribute(page.lastModified || \"\")}\">${escapeHtml(formatted)}</time>`;\n  const label = config.label.trim();\n  return label ? `${escapeHtml(label)} ${time}` : time;\n}\n\nfunction resolveReadingTimeDisplayConfig(\n  docs: FarmDocsResolvedConfig,\n): ReadingTimeDisplayConfig | null {\n  const raw = docs.config.readingTime;\n  if (raw === undefined || raw === false) return null;\n\n  const options = isObjectRecord(raw) ? raw : {};\n  if (isObjectRecord(raw) && options.enabled === false) return null;\n\n  const wordsPerMinute =\n    typeof options.wordsPerMinute === \"number\" && options.wordsPerMinute > 0\n      ? options.wordsPerMinute\n      : 220;\n\n  return {\n    wordsPerMinute,\n    format: options.format === \"short\" ? \"short\" : \"long\",\n    includeCode: options.includeCode === true,\n  };\n}\n\nfunction countMarkdownWords(body: string, includeCode: boolean): number {\n  const readable = (\n    includeCode ? body : body.replace(/```[\\s\\S]*?```/g, \" \").replace(/`[^`]*`/g, \" \")\n  )\n    .replace(/!\\[[^\\]]*]\\([^)]*\\)/g, \" \")\n    .replace(/\\[([^\\]]+)]\\([^)]*\\)/g, \"$1\")\n    .replace(/<[^>]+>/g, \" \")\n    .replace(/[#>*_~`|:-]/g, \" \");\n\n  return readable.match(/[A-Za-z0-9]+(?:[-'][A-Za-z0-9]+)*/g)?.length ?? 0;\n}\n\nfunction renderReadingTimeMeta(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  const config = resolveReadingTimeDisplayConfig(docs);\n  if (!config) return \"\";\n\n  const words = countMarkdownWords(page.body, config.includeCode);\n  const minutes = Math.max(1, Math.ceil(words / config.wordsPerMinute));\n  const label = config.format === \"short\" ? `${minutes} min` : `${minutes} min read`;\n\n  return `<div class=\"fd-page-meta not-prose\" data-page-reading-time>\n  <span class=\"fd-page-meta-dot\" aria-hidden=\"true\">·</span>\n  <span class=\"fd-page-meta-item\">${escapeHtml(label)}</span>\n</div>`;\n}\n\nfunction renderPixelPageActions(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  const copyMarkdown = resolveCopyMarkdownActionConfig(docs);\n  if (!copyMarkdown) return \"\";\n\n  const markdownUrl = `${page.href}.md`;\n  const includeTitle = copyMarkdown.includeTitle ? \"true\" : \"false\";\n\n  return `<div class=\"fd-page-actions\" data-page-actions data-actions-alignment=\"${resolvePageActionsAlignment(docs)}\">\n  <button\n    type=\"button\"\n    class=\"fd-page-action-btn\"\n    data-page-action=\"copy-markdown\"\n    data-copied=\"false\"\n    data-markdown-url=\"${escapeAttribute(markdownUrl)}\"\n    data-copy-markdown-format=\"${copyMarkdown.format}\"\n    data-copy-markdown-include-title=\"${includeTitle}\"\n    data-copy-label=\"${escapeAttribute(copyMarkdown.label)}\"\n    data-copied-label=\"${escapeAttribute(copyMarkdown.copiedLabel)}\"\n    aria-label=\"${escapeAttribute(copyMarkdown.label)}\"\n    title=\"${escapeAttribute(copyMarkdown.label)}\"\n  >\n    <svg class=\"fd-page-action-copy-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg>\n    <svg class=\"fd-page-action-check-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M20 6 9 17l-5-5\"></path></svg>\n    <span data-page-action-label>${escapeHtml(copyMarkdown.label)}</span>\n  </button>\n</div>`;\n}\n\nfunction renderBelowTitleMeta(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  const lastUpdated = renderLastUpdatedText(page, docs, \"below-title\");\n  const actions = renderPixelPageActions(page, docs);\n  const readingTime = renderReadingTimeMeta(page, docs);\n  if (!lastUpdated && !actions && !readingTime) return \"\";\n\n  return `<div class=\"fd-below-title-block not-prose\">\n  ${lastUpdated ? `<p class=\"fd-last-updated-inline\">${lastUpdated}</p>` : \"\"}\n  ${actions}\n  ${readingTime}\n</div>`;\n}\n\nfunction renderMarkdownHtmlWithTitleMeta(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n  html: string,\n): string {\n  const meta = renderBelowTitleMeta(page, docs);\n  if (!meta) return html;\n\n  const withTitleMeta = html.replace(/(<h1\\b[\\s\\S]*?<\\/h1>)/, `$1\\n${meta}`);\n  return withTitleMeta === html ? `${meta}\\n${html}` : withTitleMeta;\n}\n\nfunction renderPixelPageFooter(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  const lastUpdated = renderLastUpdatedText(page, docs, \"footer\");\n  if (!lastUpdated) return \"\";\n\n  return `<div class=\"not-prose fd-page-footer\">\n  <span class=\"fd-last-updated-footer\">${lastUpdated}</span>\n</div>`;\n}\n\nfunction getDocsLlmsOptions(docs: FarmDocsResolvedConfig, request: Request) {\n  const configured =\n    typeof docs.config.llmsTxt === \"object\" && docs.config.llmsTxt !== null\n      ? docs.config.llmsTxt\n      : {};\n  return {\n    enabled: true,\n    baseUrl: new URL(request.url).origin,\n    siteTitle: getDocsTitle(docs),\n    siteDescription: getDocsDescription(docs),\n    ...configured,\n  };\n}\n\nfunction getDocsDiscoveryOptions(docs: FarmDocsResolvedConfig, request: Request) {\n  return {\n    origin: new URL(request.url).origin,\n    entry: docs.entry,\n    i18n: null,\n    search: docs.config.search ?? true,\n    mcp: {\n      enabled: false,\n      route: \"/api/docs/mcp\",\n      name: `${getDocsTitle(docs)} MCP`,\n      version: \"1\",\n      tools: {\n        listDocs: false,\n        listPages: false,\n        readPage: false,\n        searchDocs: false,\n        getNavigation: false,\n        getCodeExamples: false,\n        getConfigSchema: false,\n      },\n    },\n    feedback: undefined,\n    llms: getDocsLlmsOptions(docs, request),\n    sitemap: docs.config.sitemap ?? true,\n    robots: docs.config.robots ?? true,\n    openapi: undefined,\n    markdown: {\n      acceptHeader: true,\n      signatureAgentHeader: true,\n    },\n  };\n}\n\nfunction createFarmDocsPublicResponse(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n  request: Request,\n): Response | null {\n  const url = new URL(request.url);\n  let loadedPages: LoadedFarmDocsPage[] | undefined;\n  const getPages = () => (loadedPages ??= getLoadedDocsPages(contentDir, docs));\n  const sitemapManifest = () =>\n    buildDocsSitemapManifest({\n      pages: getPages().map(toDocsSitemapPage),\n      entry: docs.entry,\n      siteTitle: getDocsTitle(docs),\n      baseUrl: url.origin,\n    });\n  const textHeaders = (contentType: string) => ({\n    \"Content-Type\": contentType,\n    \"Cache-Control\": \"public, max-age=60\",\n  });\n\n  const llmsFormat = resolveDocsLlmsTxtFormat(url);\n  if (llmsFormat) {\n    const generated = renderDocsLlmsTxt(\n      getPages().map(toDocsLlmsPage),\n      getDocsLlmsOptions(docs, request),\n    );\n    return new Response(llmsFormat === \"llms-full\" ? generated.llmsFullTxt : generated.llmsTxt, {\n      status: 200,\n      headers: textHeaders(\"text/plain; charset=utf-8\"),\n    });\n  }\n\n  const sitemapFormat = resolveDocsSitemapRequest(url, docs.config.sitemap ?? true);\n  if (sitemapFormat === \"xml\") {\n    return new Response(\n      renderDocsSitemapXml(sitemapManifest(), {\n        baseUrl: url.origin,\n        includeLastmod: true,\n      }),\n      {\n        status: 200,\n        headers: textHeaders(\"application/xml; charset=utf-8\"),\n      },\n    );\n  }\n  if (sitemapFormat === \"markdown\") {\n    return new Response(\n      renderDocsSitemapMarkdown(sitemapManifest(), {\n        includeDescriptions: true,\n      }),\n      {\n        status: 200,\n        headers: textHeaders(\"text/markdown; charset=utf-8\"),\n      },\n    );\n  }\n\n  if (resolveDocsRobotsRequest(url, docs.config.robots ?? true)) {\n    return new Response(\n      renderDocsRobotsTxt({\n        entry: docs.entry,\n        sitemap: docs.config.sitemap ?? true,\n        robots: docs.config.robots ?? true,\n        baseUrl: url.origin,\n      }),\n      {\n        status: 200,\n        headers: textHeaders(\"text/plain; charset=utf-8\"),\n      },\n    );\n  }\n\n  if (isDocsAgentDiscoveryRequest(url)) {\n    const spec = buildDocsAgentDiscoverySpec(getDocsDiscoveryOptions(docs, request));\n    const title = getDocsTitle(docs);\n    return new Response(\n      JSON.stringify({\n        ...spec,\n        name: title,\n        site: {\n          ...spec.site,\n          title,\n          description: getDocsDescription(docs),\n          entry: docs.entry,\n        },\n      }),\n      {\n        status: 200,\n        headers: textHeaders(\"application/json; charset=utf-8\"),\n      },\n    );\n  }\n\n  if (isDocsAgentsRequest(url)) {\n    return new Response(\n      `${renderDocsAgentsDocument(getDocsDiscoveryOptions(docs, request)).trim()}\\n`,\n      {\n        status: 200,\n        headers: textHeaders(\"text/markdown; charset=utf-8\"),\n      },\n    );\n  }\n\n  if (isDocsSkillRequest(url)) {\n    return new Response(\n      `${renderDocsSkillDocument(getDocsDiscoveryOptions(docs, request)).trim()}\\n`,\n      {\n        status: 200,\n        headers: textHeaders(\"text/markdown; charset=utf-8\"),\n      },\n    );\n  }\n\n  return null;\n}\n\nfunction omitFarmDocsHeadBody(request: Request, response: Response): Response {\n  if (request.method !== \"HEAD\") return response;\n  return new Response(null, {\n    status: response.status,\n    statusText: response.statusText,\n    headers: response.headers,\n  });\n}\n\nfunction escapeHtml(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\");\n}\n\nfunction shouldReturnMarkdown(request: Request): boolean {\n  const url = new URL(request.url);\n  if (url.pathname.endsWith(\".md\")) return true;\n\n  const accept = request.headers.get(\"accept\");\n  // Substring matching cannot see `q=0`, so `text/markdown;q=0` (an explicit\n  // refusal) used to be served Markdown anyway. Only an exact entry counts:\n  // `*/*` means \"anything\", not \"Markdown over HTML\".\n  const markdown = Math.max(\n    farmAcceptQuality(accept, \"text/markdown\"),\n    farmAcceptQuality(accept, \"text/plain\"),\n  );\n  if (markdown <= 0) return false;\n\n  // A client listing text/plain as a low-quality fallback behind text/html\n  // wants the HTML page; serve Markdown only when it is at least as welcome.\n  return markdown >= farmAcceptQuality(accept, \"text/html\", { wildcards: true });\n}\n\nfunction escapeAttribute(value: string): string {\n  return escapeHtml(value).replace(/'/g, \"&#39;\");\n}\n\nfunction slugify(value: string): string {\n  return value\n    .toLowerCase()\n    .replace(/<[^>]+>/g, \"\")\n    .replace(/`([^`]+)`/g, \"$1\")\n    .replace(/[^a-z0-9]+/g, \"-\")\n    .replace(/^-|-$/g, \"\");\n}\n\nfunction createSlugger() {\n  const seen = new Map<string, number>();\n\n  return (value: string) => {\n    const base = slugify(value) || \"section\";\n    const count = seen.get(base) || 0;\n    seen.set(base, count + 1);\n    return count === 0 ? base : `${base}-${count + 1}`;\n  };\n}\n\nfunction stripHtml(value: string): string {\n  return value.replace(/<[^>]+>/g, \"\");\n}\n\nfunction getCodeFence(line: string): { marker: \"`\" | \"~\"; length: number } | null {\n  const match = /^(?: {0,3})(`{3,}|~{3,})/.exec(line);\n  const value = match?.[1];\n  if (!value) return null;\n  return { marker: value[0] as \"`\" | \"~\", length: value.length };\n}\n\nfunction isClosingCodeFence(line: string, fence: { marker: \"`\" | \"~\"; length: number }): boolean {\n  const trimmed = line.trim();\n  return (\n    trimmed.length >= fence.length && Array.from(trimmed).every((char) => char === fence.marker)\n  );\n}\n\nfunction stripMdxRuntimeSyntax(body: string): string {\n  const output: string[] = [];\n  let fence: { marker: \"`\" | \"~\"; length: number } | null = null;\n\n  for (const line of body.split(\"\\n\")) {\n    const nextFence = getCodeFence(line);\n    if (fence) {\n      output.push(line);\n      if (nextFence && nextFence.marker === fence.marker && isClosingCodeFence(line, fence)) {\n        fence = null;\n      }\n      continue;\n    }\n\n    if (nextFence) {\n      fence = nextFence;\n      output.push(line);\n      continue;\n    }\n\n    if (/^\\s*import\\s.+$/.test(line) || /^\\s*export\\s+(const|default)\\s.+$/.test(line)) {\n      continue;\n    }\n\n    output.push(line);\n  }\n\n  return output.join(\"\\n\");\n}\n\nfunction unescapeHtml(value: string): string {\n  return value\n    .replace(/&quot;/g, '\"')\n    .replace(/&#39;/g, \"'\")\n    .replace(/&lt;/g, \"<\")\n    .replace(/&gt;/g, \">\")\n    .replace(/&amp;/g, \"&\");\n}\n\nconst CODE_LANGUAGE_LABELS = new Set([\n  \"bash\",\n  \"cjs\",\n  \"cmd\",\n  \"console\",\n  \"css\",\n  \"html\",\n  \"javascript\",\n  \"js\",\n  \"json\",\n  \"jsx\",\n  \"md\",\n  \"mdx\",\n  \"shell\",\n  \"sh\",\n  \"terminal\",\n  \"text\",\n  \"ts\",\n  \"tsx\",\n  \"txt\",\n  \"typescript\",\n  \"yaml\",\n  \"yml\",\n  \"zsh\",\n]);\n\nconst EXTENSIONLESS_CODE_FILENAMES = new Set([\n  \"dockerfile\",\n  \"makefile\",\n  \"procfile\",\n  \"readme\",\n  \"license\",\n]);\n\nfunction isCodePathLabel(label: string): boolean {\n  const trimmed = label.trim();\n  if (!trimmed || /\\s/.test(trimmed)) return false;\n\n  const lower = trimmed.toLowerCase();\n  if (CODE_LANGUAGE_LABELS.has(lower)) return false;\n\n  const fileName = trimmed.split(/[\\\\/]/).filter(Boolean).pop() || trimmed;\n  const lowerFileName = fileName.toLowerCase();\n  if (EXTENSIONLESS_CODE_FILENAMES.has(lowerFileName)) return true;\n  if (fileName.startsWith(\".\") && fileName.length > 1) return true;\n\n  return /\\.[a-z0-9][a-z0-9-]*$/i.test(fileName);\n}\n\nfunction parseCodeInfo(info: string | undefined): {\n  language: string;\n  label: string;\n  hasExplicitLabel: boolean;\n} {\n  const source = (info || \"\").trim();\n  const language = source.match(/^\\S+/)?.[0] || \"text\";\n  const explicitLabel = source\n    .match(/\\b(?:title|filename|file|label|name)=[\"']([^\"']+)[\"']/)?.[1]\n    ?.trim();\n  return { language, label: explicitLabel || language, hasExplicitLabel: Boolean(explicitLabel) };\n}\n\nfunction getStandaloneCodeLabel(line: string): string | null {\n  const trimmed = line.trim();\n  const match = /^(?:\\*\\*([^*]+)\\*\\*|__([^_]+)__|`([^`]+)`)$/u.exec(trimmed);\n  const label = match?.[1] || match?.[2] || match?.[3];\n  return label?.trim() || null;\n}\n\nfunction hasCodeFenceTitle(info: string): boolean {\n  return /\\b(?:title|filename|file|label|name)=[\"'][^\"']+[\"']/.test(info);\n}\n\nfunction escapeCodeFenceTitle(value: string): string {\n  return value.replace(/\"/g, \"&quot;\");\n}\n\nfunction addTitleToCodeFence(line: string, title: string): string {\n  const match = /^(\\s{0,3})(`{3,}|~{3,})(.*)$/u.exec(line);\n  if (!match) return line;\n  const [, indent, marker, infoSource] = match;\n  const info = infoSource.trim();\n  if (hasCodeFenceTitle(info)) return line;\n  const suffix = `title=\"${escapeCodeFenceTitle(title)}\"`;\n  return `${indent}${marker}${info ? `${info} ${suffix}` : `text ${suffix}`}`;\n}\n\nfunction attachCodeBlockLabels(body: string): string {\n  const lines = body.split(\"\\n\");\n  const output: string[] = [];\n  let fence: { marker: \"`\" | \"~\"; length: number } | null = null;\n\n  for (let index = 0; index < lines.length; index += 1) {\n    const line = lines[index] || \"\";\n    const nextFence = getCodeFence(line);\n\n    if (fence) {\n      output.push(line);\n      if (nextFence && nextFence.marker === fence.marker && isClosingCodeFence(line, fence)) {\n        fence = null;\n      }\n      continue;\n    }\n\n    if (nextFence) {\n      fence = nextFence;\n      output.push(line);\n      continue;\n    }\n\n    const label = getStandaloneCodeLabel(line);\n    if (!label) {\n      output.push(line);\n      continue;\n    }\n\n    let fenceIndex = index + 1;\n    while (fenceIndex < lines.length && (lines[fenceIndex] || \"\").trim() === \"\") {\n      fenceIndex += 1;\n    }\n\n    const labeledFence = getCodeFence(lines[fenceIndex] || \"\");\n    if (!labeledFence) {\n      output.push(line);\n      continue;\n    }\n\n    output.push(addTitleToCodeFence(lines[fenceIndex] || \"\", label));\n    fence = labeledFence;\n    index = fenceIndex;\n  }\n\n  return output.join(\"\\n\");\n}\n\nfunction highlightCodeBlock(code: string): string {\n  return highlight(code.replace(/\\n$/, \"\")).replace(/<\\/span>\\n<span/g, \"</span><span\");\n}\n\nfunction renderCodeCopyButton(className = \"code-copy\"): string {\n  return `<button class=\"${className}\" type=\"button\" data-copied=\"false\" aria-label=\"Copy code\" title=\"Copy code\" onclick=\"navigator.clipboard?.writeText(this.closest('figure').querySelector('code').innerText); this.dataset.copied='true'; this.setAttribute('aria-label','Copied'); this.title='Copied'; clearTimeout(this._copyTimer); this._copyTimer=setTimeout(() => { this.dataset.copied='false'; this.setAttribute('aria-label','Copy code'); this.title='Copy code'; }, 4500);\"><svg class=\"code-copy-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg><svg class=\"code-copy-check\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M20 6 9 17l-5-5\"></path></svg></button>`;\n}\n\nfunction renderMarkdownDocument(\n  body: string,\n  depth: number,\n): { html: string; tocItems: TocItem[] } {\n  const slug = createSlugger();\n  const renderer = new Renderer();\n  const maxLevel = Math.max(2, Math.min(depth, 6));\n  const tocItems: TocItem[] = [];\n\n  renderer.heading = (text, level, raw) => {\n    const title = raw || stripHtml(text);\n    const id = slug(title);\n    if (level >= 2 && level <= maxLevel) {\n      tocItems.push({ id, title, level });\n    }\n    return `<h${level} id=\"${escapeAttribute(id)}\"><a class=\"heading-anchor\" href=\"#${escapeAttribute(id)}\">${text}</a></h${level}>\\n`;\n  };\n\n  renderer.code = (code, infostring, escaped) => {\n    const { language, label, hasExplicitLabel } = parseCodeInfo(infostring);\n    const rawCode = escaped ? unescapeHtml(code) : code;\n    const highlighted = highlightCodeBlock(rawCode);\n    const shouldRenderHeader = hasExplicitLabel && isCodePathLabel(label);\n    const header = shouldRenderHeader\n      ? `<div class=\"code-block-header\">\n    <span class=\"code-block-title\">${escapeHtml(label)}</span>\n    ${renderCodeCopyButton()}\n  </div>`\n      : renderCodeCopyButton(\"code-copy code-copy-floating\");\n\n    return `<figure class=\"shiki code-block ${shouldRenderHeader ? \"code-block-framed\" : \"code-block-plain\"}\" data-language=\"${escapeAttribute(language)}\">\n  ${header}\n  <pre><code class=\"sh-code language-${escapeAttribute(language)}\">${highlighted}</code></pre>\n</figure>\\n`;\n  };\n\n  renderer.table = (header, body) =>\n    `<div class=\"fd-table-wrapper table-wrap relative overflow-auto prose-no-margin my-6\"><table><thead>${header}</thead><tbody>${body}</tbody></table></div>\\n`;\n\n  renderer.blockquote = (quote) => `<blockquote>${quote}</blockquote>\\n`;\n  renderer.codespan = (code) => `<code>${escapeHtml(code)}</code>`;\n\n  renderer.link = (href, title, text) => {\n    const safeHref = href || \"\";\n    const titleAttribute = title ? ` title=\"${escapeAttribute(title)}\"` : \"\";\n    return `<a href=\"${escapeAttribute(safeHref)}\"${titleAttribute}>${text}</a>`;\n  };\n\n  renderer.image = (href, title, text) => {\n    const titleAttribute = title ? ` title=\"${escapeAttribute(title)}\"` : \"\";\n    return `<img src=\"${escapeAttribute(href)}\" alt=\"${escapeAttribute(text)}\"${titleAttribute}>`;\n  };\n\n  const html = marked(attachCodeBlockLabels(stripMdxRuntimeSyntax(body)), {\n    async: false,\n    breaks: false,\n    gfm: true,\n    renderer,\n  }) as string;\n\n  return { html: html.trim(), tocItems };\n}\n\ninterface TocItem {\n  id: string;\n  title: string;\n  level: number;\n}\n\nfunction getThemeUI(docs: FarmDocsResolvedConfig): Record<string, any> {\n  const theme = docs.config.theme;\n  return theme && typeof theme === \"object\" && \"ui\" in theme && typeof theme.ui === \"object\"\n    ? (theme.ui as Record<string, any>)\n    : {};\n}\n\nfunction getThemeName(docs: FarmDocsResolvedConfig): string {\n  const theme = docs.config.theme;\n  return theme && typeof theme === \"object\" && \"name\" in theme\n    ? String((theme as { name?: unknown }).name || \"farm-docs\")\n    : \"farm-docs\";\n}\n\nfunction getThemeTocDepth(docs: FarmDocsResolvedConfig): number {\n  const toc = getThemeUI(docs).layout?.toc;\n  return toc && typeof toc === \"object\" && typeof toc.depth === \"number\" ? toc.depth : 3;\n}\n\nconst SIDEBAR_SECTION_ORDER = [\n  \"Start\",\n  \"Core\",\n  \"Data and APIs\",\n  \"Integrations\",\n  \"Runtime\",\n  \"Content\",\n  \"Extending\",\n  \"Reference\",\n];\n\nconst SIDEBAR_PAGE_ORDER = new Map(\n  [\n    \"\",\n    \"getting-started\",\n    \"project-structure\",\n    \"configuration\",\n    \"routing\",\n    \"layouts\",\n    \"server-rendering\",\n    \"middleware\",\n    \"query\",\n    \"api-routes\",\n    \"api-client\",\n    \"storage\",\n    \"integrations\",\n    \"integrations/stripe\",\n    \"integrations/autumn\",\n    \"integrations/polar\",\n    \"integrations/auth\",\n    \"integrations/email\",\n    \"integrations/jobs\",\n    \"integrations/unkey\",\n    \"integrations/ui-registry\",\n    \"integrations/orm-storage\",\n    \"cache-ppr\",\n    \"observability\",\n    \"deployment\",\n    \"docs-engine\",\n    \"markdown\",\n    \"openapi\",\n    \"plugins\",\n    \"plugins/create-plugin\",\n    \"cli\",\n    \"examples\",\n    \"reference\",\n  ].map((slug, index) => [slug, index]),\n);\n\ntype SidebarNavigationItem = {\n  label?: string;\n  icon?: string;\n  slug?: string;\n  href?: string;\n  children: SidebarNavigationItem[];\n};\n\nfunction isSidebarNavigationItem(\n  value: SidebarNavigationItem | null,\n): value is SidebarNavigationItem {\n  return value !== null;\n}\n\nfunction compareSidebarPages(a: FarmDocsPage, b: FarmDocsPage): number {\n  const aOrder = SIDEBAR_PAGE_ORDER.get(a.slug) ?? 1000;\n  const bOrder = SIDEBAR_PAGE_ORDER.get(b.slug) ?? 1000;\n  return aOrder - bOrder || a.title.localeCompare(b.title);\n}\n\nfunction getSidebarSection(page: FarmDocsPage): string {\n  if (page.section) return page.section;\n  if (page.slug.startsWith(\"integrations/\")) return \"Integrations\";\n  if (page.slug.startsWith(\"plugins/\")) return \"Extending\";\n  return \"Reference\";\n}\n\nfunction sidebarIdFor(section: string): string {\n  return `sidebar-${slugify(section)}`;\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction readString(value: unknown): string | undefined {\n  return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction readOptionalString(value: unknown): string | undefined {\n  return typeof value === \"string\" ? value.trim() : undefined;\n}\n\nfunction normalizeSidebarSlug(value: string): string {\n  if (value === \"/\" || value === \".\") return \"\";\n  return trimSlashes(value);\n}\n\nfunction getSidebarNavigation(docs: FarmDocsResolvedConfig): SidebarNavigationItem[] {\n  const navigation = docs.config.navigation;\n  if (!isObjectRecord(navigation) || !Array.isArray(navigation.sidebar)) return [];\n  return navigation.sidebar.map(normalizeSidebarNavigationItem).filter(isSidebarNavigationItem);\n}\n\nfunction normalizeSidebarNavigationItem(value: unknown): SidebarNavigationItem | null {\n  if (!isObjectRecord(value)) return null;\n\n  const label = readString(value.label) ?? readString(value.title);\n  const icon = readString(value.icon);\n  const slug = readOptionalString(value.slug) ?? readOptionalString(value.path);\n  const href = readString(value.href) ?? readString(value.url);\n  const rawChildren = Array.isArray(value.children)\n    ? value.children\n    : Array.isArray(value.items)\n      ? value.items\n      : [];\n  const children = rawChildren.map(normalizeSidebarNavigationItem).filter(isSidebarNavigationItem);\n\n  if (!label && !slug && !href && children.length === 0) return null;\n  return {\n    ...(label ? { label } : {}),\n    ...(icon ? { icon } : {}),\n    ...(slug !== undefined ? { slug: normalizeSidebarSlug(slug) } : {}),\n    ...(href ? { href } : {}),\n    children,\n  };\n}\n\nfunction createSidebarPageMaps(pages: FarmDocsPage[]) {\n  return {\n    bySlug: new Map(pages.map((page) => [page.slug, page])),\n    byHref: new Map(pages.map((page) => [page.href, page])),\n  };\n}\n\nfunction resolveConfiguredSidebarPage(\n  item: SidebarNavigationItem,\n  maps: ReturnType<typeof createSidebarPageMaps>,\n): FarmDocsPage | undefined {\n  if (item.slug !== undefined) return maps.bySlug.get(item.slug);\n  if (item.href) return maps.byHref.get(item.href);\n  return undefined;\n}\n\nfunction getSidebarIconRegistry(docs: FarmDocsResolvedConfig): Record<string, unknown> {\n  return isObjectRecord(docs.config.icons) ? docs.config.icons : {};\n}\n\nfunction renderConfiguredIconSvg(value: unknown): string {\n  if (typeof value !== \"string\") return \"\";\n  const icon = value.trim();\n  if (!icon) return \"\";\n  if (/^<svg[\\s>]/i.test(icon)) return icon;\n  if (/^<(path|circle|rect|line|polyline|polygon|ellipse|g)\\b/i.test(icon)) {\n    return `<svg viewBox=\"0 0 24 24\" focusable=\"false\">${icon}</svg>`;\n  }\n  return \"\";\n}\n\nfunction renderSidebarIcon(\n  docs: FarmDocsResolvedConfig,\n  icon: string | undefined,\n  className = \"sidebar-icon fd-sidebar-icon\",\n): string {\n  if (!icon) return \"\";\n  const iconRegistry = getSidebarIconRegistry(docs);\n  const configuredIcon = iconRegistry[icon] ?? icon;\n  const svg = renderConfiguredIconSvg(configuredIcon);\n  if (!svg) return \"\";\n  return `<span class=\"${className}\" data-sidebar-icon=\"${escapeAttribute(icon)}\" aria-hidden=\"true\">${svg}</span>`;\n}\n\nfunction renderSidebarLabel(\n  docs: FarmDocsResolvedConfig,\n  icon: string | undefined,\n  label: string,\n  className: string,\n): string {\n  return `<span class=\"${className}\">${renderSidebarIcon(docs, icon)}<span class=\"sidebar-label-text\">${escapeHtml(label)}</span></span>`;\n}\n\nfunction getSidebarPageLabel(item: FarmDocsPage, configured?: SidebarNavigationItem): string {\n  if (configured?.label) return configured.label;\n  if (item.slug === \"\") return \"Why?\";\n  if (item.slug === \"integrations\") return \"Overview\";\n  if (item.slug === \"integrations/ui-registry\") return \"UI Registry\";\n  if (item.slug === \"integrations/orm-storage\") return \"ORM Storage\";\n  if (item.slug.startsWith(\"integrations/\")) {\n    return item.title.replace(/\\s+Integrations?$/i, \"\");\n  }\n  return item.title;\n}\n\nfunction renderSidebarLink(\n  item: FarmDocsPage,\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n  configured?: SidebarNavigationItem,\n): string {\n  const active = item.href === activeHref;\n  return `<a class=\"fd-sidebar-link${active ? \" fd-sidebar-link-active\" : \"\"}\" data-active=\"${active ? \"true\" : \"false\"}\" href=\"${escapeAttribute(item.href)}\">${renderSidebarLabel(docs, configured?.icon, getSidebarPageLabel(item, configured), \"sidebar-link-label fd-sidebar-link-label\")}</a>`;\n}\n\nfunction collectConfiguredSidebarPages(\n  items: SidebarNavigationItem[],\n  maps: ReturnType<typeof createSidebarPageMaps>,\n  seen = new Set<string>(),\n): FarmDocsPage[] {\n  const ordered: FarmDocsPage[] = [];\n  for (const item of items) {\n    const page = resolveConfiguredSidebarPage(item, maps);\n    if (page && !seen.has(page.slug)) {\n      seen.add(page.slug);\n      ordered.push(page);\n    }\n    ordered.push(...collectConfiguredSidebarPages(item.children, maps, seen));\n  }\n  return ordered;\n}\n\nfunction getOrderedSidebarPages(\n  pages: FarmDocsPage[],\n  docs?: FarmDocsResolvedConfig,\n): FarmDocsPage[] {\n  if (!docs) return [...pages].sort(compareSidebarPages);\n\n  const maps = createSidebarPageMaps(pages);\n  const configuredPages = collectConfiguredSidebarPages(getSidebarNavigation(docs), maps);\n  if (configuredPages.length === 0) return [...pages].sort(compareSidebarPages);\n\n  const configuredSlugs = new Set(configuredPages.map((page) => page.slug));\n  const remainingPages = pages\n    .filter((page) => !configuredSlugs.has(page.slug))\n    .sort(compareSidebarPages);\n  return [...configuredPages, ...remainingPages];\n}\n\nfunction renderExternalSidebarLink(\n  item: SidebarNavigationItem,\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  if (!item.href || !item.label) return \"\";\n  const active = item.href === activeHref;\n  return `<a class=\"fd-sidebar-link${active ? \" fd-sidebar-link-active\" : \"\"}\" data-active=\"${active ? \"true\" : \"false\"}\" href=\"${escapeAttribute(item.href)}\">${renderSidebarLabel(docs, item.icon, item.label, \"sidebar-link-label fd-sidebar-link-label\")}</a>`;\n}\n\nfunction renderConfiguredSidebarSubgroup(\n  item: SidebarNavigationItem,\n  childHtml: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const label = item.label;\n  if (!label) return childHtml;\n  return `<div class=\"sidebar-subgroup fd-sidebar-folder\" data-sidebar-subgroup=\"${escapeAttribute(slugify(label))}\">\n  <div class=\"sidebar-subgroup-title fd-sidebar-folder-trigger\">${renderSidebarLabel(docs, item.icon, label, \"sidebar-subgroup-label\")}</div>\n  <div class=\"sidebar-subgroup-content fd-sidebar-folder-content\">\n${childHtml}\n  </div>\n</div>`;\n}\n\nfunction renderConfiguredSidebarItems(\n  items: SidebarNavigationItem[],\n  maps: ReturnType<typeof createSidebarPageMaps>,\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const renderedItems: string[] = [];\n  for (const item of items) {\n    const page = resolveConfiguredSidebarPage(item, maps);\n    const childHtml = renderConfiguredSidebarItems(item.children, maps, activeHref, docs);\n\n    if (item.children.length > 0) {\n      renderedItems.push(renderConfiguredSidebarSubgroup(item, childHtml, docs));\n      continue;\n    }\n\n    const linkHtml = page\n      ? renderSidebarLink(page, activeHref, docs, item)\n      : renderExternalSidebarLink(item, activeHref, docs);\n    if (linkHtml) renderedItems.push(linkHtml);\n  }\n  return renderedItems.join(\"\\n\");\n}\n\nfunction renderConfiguredSidebarSection(\n  section: SidebarNavigationItem,\n  maps: ReturnType<typeof createSidebarPageMaps>,\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const label = section.label || \"Docs\";\n  const id = sidebarIdFor(label);\n  const links = renderConfiguredSidebarItems(section.children, maps, activeHref, docs);\n  return `<div class=\"sidebar-folder fd-sidebar-folder\" data-state=\"open\">\n  <button class=\"text-fd-muted-foreground sidebar-folder-trigger fd-sidebar-folder-trigger\" type=\"button\" aria-controls=\"${escapeAttribute(id)}\" aria-expanded=\"true\">${renderSidebarLabel(docs, section.icon, label, \"sidebar-folder-label\")}</button>\n  <div id=\"${escapeAttribute(id)}\" class=\"overflow-hidden sidebar-folder-content fd-sidebar-folder-content\" data-state=\"open\">\n${links}\n  </div>\n</div>`;\n}\n\nfunction renderAutoSidebarSectionItems(\n  items: FarmDocsPage[],\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  return [...items]\n    .sort(compareSidebarPages)\n    .map((item) => renderSidebarLink(item, activeHref, docs))\n    .join(\"\\n\");\n}\n\nfunction renderPixelNavItems(\n  pages: FarmDocsPage[],\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const configuredSidebar = getSidebarNavigation(docs);\n  if (configuredSidebar.length > 0) {\n    const maps = createSidebarPageMaps(pages);\n    const renderedSections = configuredSidebar\n      .map((section) => {\n        if (section.children.length > 0) {\n          return renderConfiguredSidebarSection(section, maps, activeHref, docs);\n        }\n        const page = resolveConfiguredSidebarPage(section, maps);\n        return page\n          ? renderSidebarLink(page, activeHref, docs, section)\n          : renderExternalSidebarLink(section, activeHref, docs);\n      })\n      .filter(Boolean)\n      .join(\"\\n\");\n\n    return `<div class=\"sidebar-scroll overscroll-contain fd-sidebar-nav\">\n  <div class=\"sidebar-tree\">\n${renderedSections}\n  </div>\n</div>`;\n  }\n\n  const groups = new Map<string, FarmDocsPage[]>();\n  for (const item of pages) {\n    const group = item.slug === \"\" ? \"Start\" : getSidebarSection(item);\n    const entries = groups.get(group) ?? [];\n    entries.push(item);\n    groups.set(group, entries);\n  }\n\n  const renderedSections = Array.from(groups.entries())\n    .sort(([a], [b]) => {\n      const aOrder = SIDEBAR_SECTION_ORDER.indexOf(a);\n      const bOrder = SIDEBAR_SECTION_ORDER.indexOf(b);\n      return (aOrder === -1 ? 100 : aOrder) - (bOrder === -1 ? 100 : bOrder) || a.localeCompare(b);\n    })\n    .map(([section, items]) => {\n      const id = sidebarIdFor(section);\n      const links = renderAutoSidebarSectionItems(items, activeHref, docs);\n      return `<div class=\"sidebar-folder fd-sidebar-folder\" data-state=\"open\">\n  <button class=\"text-fd-muted-foreground sidebar-folder-trigger fd-sidebar-folder-trigger\" type=\"button\" aria-controls=\"${escapeAttribute(id)}\" aria-expanded=\"true\">${renderSidebarLabel(docs, undefined, section, \"sidebar-folder-label\")}</button>\n  <div id=\"${escapeAttribute(id)}\" class=\"overflow-hidden sidebar-folder-content fd-sidebar-folder-content\" data-state=\"open\">\n${links}\n  </div>\n</div>`;\n    })\n    .join(\"\\n\");\n\n  return `<div class=\"sidebar-scroll overscroll-contain fd-sidebar-nav\">\n  <div class=\"sidebar-tree\">\n${renderedSections}\n  </div>\n</div>`;\n}\n\nfunction renderPixelPageNav(\n  pages: FarmDocsPage[],\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const orderedPages = getOrderedSidebarPages(pages, docs);\n  const activeIndex = orderedPages.findIndex((item) => item.href === activeHref);\n  if (activeIndex === -1) return \"\";\n\n  const previous = orderedPages[activeIndex - 1];\n  const next = orderedPages[activeIndex + 1];\n  if (!previous && !next) return \"\";\n\n  const renderChevron = (direction: \"prev\" | \"next\") =>\n    `<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><polyline points=\"${direction === \"prev\" ? \"15 18 9 12 15 6\" : \"9 18 15 12 9 6\"}\" /></svg>`;\n  const renderCard = (item: FarmDocsPage, direction: \"prev\" | \"next\") =>\n    `<a class=\"fd-page-nav-card fd-page-nav-${direction}\" href=\"${escapeAttribute(item.href)}\">\n  <span class=\"fd-page-nav-title fd-page-nav-title-${direction}\">${direction === \"prev\" ? `${renderChevron(direction)}${escapeHtml(item.title)}` : `${escapeHtml(item.title)}${renderChevron(direction)}`}</span>\n  <span class=\"fd-page-nav-description\">${direction === \"prev\" ? \"Previous Page\" : \"Next Page\"}</span>\n</a>`;\n\n  return `<nav class=\"not-prose fd-page-nav\" aria-label=\"Page navigation\">\n  ${previous ? renderCard(previous, \"prev\") : \"\"}\n  ${next ? renderCard(next, \"next\") : \"\"}\n</nav>`;\n}\n\nfunction titleizePathSegment(value: string): string {\n  return value.replace(/[-_]+/g, \" \").replace(/\\b\\w/g, (character) => character.toUpperCase());\n}\n\nfunction isBreadcrumbEnabled(docs: FarmDocsResolvedConfig): boolean {\n  const breadcrumb = docs.config.breadcrumb;\n  if (breadcrumb === false) return false;\n  if (breadcrumb && typeof breadcrumb === \"object\" && \"enabled\" in breadcrumb) {\n    return (breadcrumb as { enabled?: unknown }).enabled !== false;\n  }\n  return true;\n}\n\nfunction renderPixelBreadcrumb(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  if (!isBreadcrumbEnabled(docs)) return \"\";\n\n  const segments = trimSlashes(page.slug).split(\"/\").filter(Boolean);\n  if (segments.length < 2) return \"\";\n\n  const parentSegments = segments.slice(0, -1);\n  const parentSegment = parentSegments[parentSegments.length - 1];\n  const currentSegment = segments[segments.length - 1];\n  const entry = normalizeEntry(docs.entry);\n  const parentPath = parentSegments.join(\"/\");\n  const parentHref = entry === \"/\" ? `/${parentPath}` : `${entry}/${parentPath}`;\n\n  return `<nav class=\"fd-breadcrumb\" aria-label=\"Breadcrumb\">\n  <span class=\"fd-breadcrumb-item\">\n    <a class=\"fd-breadcrumb-parent fd-breadcrumb-link\" href=\"${escapeAttribute(parentHref)}\">${escapeHtml(titleizePathSegment(parentSegment))}</a>\n  </span>\n  <span class=\"fd-breadcrumb-item\">\n    <span class=\"fd-breadcrumb-sep\">/</span>\n    <span class=\"fd-breadcrumb-current\">${escapeHtml(titleizePathSegment(currentSegment))}</span>\n  </span>\n</nav>`;\n}\n\nfunction renderDocsSearchTrigger(showIcon = true, className = \"\"): string {\n  return `<button class=\"fd-docs-search-trigger ${className}\" type=\"button\" data-search-full=\"\" aria-label=\"Search documentation\" aria-haspopup=\"dialog\" aria-keyshortcuts=\"Meta+K Control+K\">\n  ${showIcon ? '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><circle cx=\"11\" cy=\"11\" r=\"7\"></circle><path d=\"m20 20-4-4\"></path></svg>' : \"\"}\n  <kbd><span>⌘</span><span>K</span></kbd>\n</button>`;\n}\n\nfunction renderDocsSearchMount(clientEntry: string): string {\n  return `<div id=\"farm-docs-search-root\" data-farm-docs-search-root data-api=\"/api/docs\"></div>\n  <script type=\"module\" src=\"${escapeAttribute(clientEntry)}\"></script>`;\n}\n\nfunction renderDocsSearchBootstrapScript(): string {\n  return `<script>${generateFarmDocsSearchBootstrapRuntime()}</script>`;\n}\n\nfunction renderPixelToc(items: TocItem[]): string {\n  if (items.length === 0) return '<p class=\"toc-empty\">No sections</p>';\n  return `<div class=\"toc-track fd-toc-list\">\n  <div class=\"toc-thumb\" data-toc-thumb style=\"clip-path: polygon(0 0px, 100% 0px, 100% 32px, 0 32px);\"></div>\n  <div class=\"toc-links\">\n${items\n  .map(\n    (item) =>\n      `<a class=\"toc-link fd-toc-link${items[0] === item ? \" fd-toc-link-active\" : \"\"}\" data-active=\"${items[0] === item ? \"true\" : \"false\"}\" data-toc-item data-depth=\"${item.level}\" href=\"#${escapeAttribute(item.id)}\">${escapeHtml(item.title)}</a>`,\n  )\n  .join(\"\\n\")}\n  </div>\n</div>`;\n}\n\nfunction renderDocsRuntimeScript(docs: FarmDocsResolvedConfig): string {\n  const docsEntry = JSON.stringify(normalizeEntry(docs.entry));\n  const reconcileHeadRuntime = `const farmNavigationHeadSelector=${JSON.stringify(FARM_NAVIGATION_HEAD_SELECTOR)};const reconcileDocsHead=(nextDoc)=>{const nextTitle=nextDoc.querySelector(\"title\");document.title=nextTitle?.textContent||\"\";document.head.querySelectorAll(farmNavigationHeadSelector).forEach((node)=>node.remove());nextDoc.head.querySelectorAll(farmNavigationHeadSelector).forEach((node)=>document.head.appendChild(document.importNode(node,true)))}`;\n  return `<script>(()=>{if(window.__farmDocsRuntime)return;window.__farmDocsRuntime=true;document.documentElement.dataset.farmDocsRuntime=\"true\";document.documentElement.dataset.farmDocsRuntimeId=Math.random().toString(36).slice(2);${reconcileHeadRuntime};const docsEntry=${docsEntry};let cleanupToc=()=>{};let closeMobileSidebar=()=>{};const normalizePath=(path)=>path.length>1?path.replace(/\\\\/+$/,\"\"):path;const isDocsPath=(path)=>{const next=normalizePath(path);const entry=normalizePath(docsEntry);if(next.endsWith(\".md\"))return false;if(entry===\"/\")return true;return next===entry||next.startsWith(entry+\"/\")};const initToc=()=>{cleanupToc();const toc=document.getElementById(\"nd-toc\");if(!toc){cleanupToc=()=>{};return}const links=Array.from(toc.querySelectorAll(\"[data-toc-item]\"));const thumb=toc.querySelector(\"[data-toc-thumb]\");const pairs=links.map((link)=>{let id=link.hash.slice(1);try{id=decodeURIComponent(id)}catch{}return{link,heading:document.getElementById(id)}}).filter((item)=>item.heading);const setActive=(active)=>{for(const {link} of pairs){const selected=link===active.link;link.dataset.active=selected?\"true\":\"false\";link.classList.toggle(\"fd-toc-link-active\",selected)}if(!thumb)return;const styles=getComputedStyle(active.link);const top=active.link.offsetTop+parseFloat(styles.paddingTop||\"0\");const bottom=active.link.offsetTop+active.link.clientHeight-parseFloat(styles.paddingBottom||\"0\");thumb.style.clipPath=\"polygon(0 \"+top+\"px,100% \"+top+\"px,100% \"+bottom+\"px,0 \"+bottom+\"px)\"};const update=()=>{if(pairs.length===0)return;const offset=Math.min(window.innerHeight*0.3,160);let active=pairs[0];for(const pair of pairs){if(pair.heading.getBoundingClientRect().top<=offset)active=pair;else break}setActive(active)};let frame=0;const schedule=()=>{if(frame)return;frame=requestAnimationFrame(()=>{frame=0;update()})};const onHashChange=()=>setTimeout(schedule,0);window.addEventListener(\"scroll\",schedule,{passive:true});window.addEventListener(\"resize\",schedule);window.addEventListener(\"hashchange\",onHashChange);cleanupToc=()=>{window.removeEventListener(\"scroll\",schedule);window.removeEventListener(\"resize\",schedule);window.removeEventListener(\"hashchange\",onHashChange);if(frame)cancelAnimationFrame(frame);frame=0};update()};const getSidebar=()=>document.getElementById(\"nd-sidebar\");const ensureActiveVisible=()=>{const sidebar=getSidebar();if(!sidebar)return;const active=sidebar.querySelector('a[data-active=\"true\"]');if(!(active instanceof HTMLElement))return;const activeRect=active.getBoundingClientRect();const sidebarRect=sidebar.getBoundingClientRect();if(activeRect.top<sidebarRect.top||activeRect.bottom>sidebarRect.bottom)sidebar.scrollTop+=activeRect.top-sidebarRect.top-(sidebar.clientHeight-activeRect.height)/2};const setSidebarActive=(path)=>{const sidebar=getSidebar();if(!sidebar)return;const current=normalizePath(path);for(const link of Array.from(sidebar.querySelectorAll(\"a[href]\"))){try{link.dataset.active=normalizePath(new URL(link.href,location.href).pathname)===current?\"true\":\"false\"}catch{}}ensureActiveVisible()};const initMobileSidebar=()=>{const layout=document.getElementById(\"nd-docs-layout\");const sidebar=getSidebar();const toggle=document.querySelector(\"[data-sidebar-toggle]\");const backdrop=document.querySelector(\"[data-sidebar-backdrop]\");if(!layout||!sidebar||!(toggle instanceof HTMLButtonElement))return;const setOpen=(open)=>{layout.dataset.sidebarOpen=open?\"true\":\"false\";sidebar.classList.toggle(\"fd-sidebar-open\",open);document.documentElement.dataset.farmDocsSidebar=open?\"open\":\"closed\";toggle.setAttribute(\"aria-expanded\",open?\"true\":\"false\");toggle.setAttribute(\"aria-label\",open?\"Close menu\":\"Open menu\")};const toggleOpen=()=>setOpen(layout.dataset.sidebarOpen!==\"true\");closeMobileSidebar=()=>setOpen(false);toggle.addEventListener(\"click\",(event)=>{event.preventDefault();toggleOpen()});backdrop?.addEventListener(\"click\",()=>closeMobileSidebar());document.addEventListener(\"keydown\",(event)=>{if(event.key===\"Escape\")closeMobileSidebar()});sidebar.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(target)closeMobileSidebar()});closeMobileSidebar()};const initSidebarScroll=()=>{const sidebar=getSidebar();if(!sidebar)return;const key=\"farmdocs:sidebar-scroll:\"+location.origin;const getStorage=()=>{try{return window.sessionStorage}catch{return null}};const readSaved=()=>{try{const raw=getStorage()?.getItem(key);if(!raw)return null;const parsed=JSON.parse(raw);return parsed&&typeof parsed===\"object\"?parsed:null}catch{return null}};const save=(path=location.pathname)=>{try{getStorage()?.setItem(key,JSON.stringify({path,scrollTop:sidebar.scrollTop}))}catch{}};const saved=readSaved();if(saved?.path===location.pathname&&Number.isFinite(Number(saved.scrollTop)))sidebar.scrollTop=Number(saved.scrollTop);ensureActiveVisible();save();sidebar.addEventListener(\"scroll\",()=>save(),{passive:true});sidebar.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(!target)return;try{save(new URL(target.href,location.href).pathname)}catch{save()}});window.addEventListener(\"beforeunload\",()=>save())};let navigateController=null;const getPageKey=(root)=>{const article=root.getElementById(\"nd-page\");if(!article)return\"\";return article.querySelector(\"h1\")?.textContent?.trim()||article.textContent?.replace(/\\\\s+/g,\" \").trim().slice(0,160)||\"\"};const swapDocsPage=(html,url)=>{const nextDoc=new DOMParser().parseFromString(html,\"text/html\");const nextArticle=nextDoc.getElementById(\"nd-page\");const currentArticle=document.getElementById(\"nd-page\");if(!nextArticle||!currentArticle)return false;const nextKey=getPageKey(nextDoc);const importedArticle=document.importNode(nextArticle,true);currentArticle.replaceWith(importedArticle);const renderedArticle=document.getElementById(\"nd-page\");if(!renderedArticle||renderedArticle===currentArticle||(nextKey&&getPageKey(document)!==nextKey))return false;const nextToc=nextDoc.getElementById(\"nd-toc\");const currentToc=document.getElementById(\"nd-toc\");if(nextToc&&currentToc)currentToc.replaceWith(document.importNode(nextToc,true));reconcileDocsHead(nextDoc);setSidebarActive(url.pathname);initToc();closeMobileSidebar();return true};const navigateDocs=async(url,{replace=false,scroll=true}={})=>{if(!isDocsPath(url.pathname))return false;if(navigateController)navigateController.abort();const controller=new AbortController();navigateController=controller;document.documentElement.dataset.farmDocsNavigating=\"true\";try{const response=await fetch(url.href,{cache:\"no-store\",headers:{accept:\"text/html\",\"x-farm-docs-navigate\":\"1\"},signal:controller.signal});if(!response.ok||!((response.headers.get(\"content-type\")||\"\").includes(\"text/html\")))return false;const html=await response.text();if(!swapDocsPage(html,url))return false;if(replace)history.replaceState({farmDocs:true},\"\",url.href);else history.pushState({farmDocs:true},\"\",url.href);if(scroll){if(url.hash){let id=url.hash.slice(1);try{id=decodeURIComponent(id)}catch{}document.getElementById(id)?.scrollIntoView({block:\"start\"})}else window.scrollTo({top:0,left:0})}return true}catch(error){if(error?.name===\"AbortError\")return true;return false}finally{if(navigateController===controller){delete document.documentElement.dataset.farmDocsNavigating;navigateController=null}}};const initClientNavigation=()=>{document.addEventListener(\"click\",(event)=>{if(event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(!target||target.target||target.hasAttribute(\"download\"))return;let url;try{url=new URL(target.href,location.href)}catch{return}if(url.origin!==location.origin||!isDocsPath(url.pathname))return;if(normalizePath(url.pathname)===normalizePath(location.pathname)&&url.hash)return;event.preventDefault();navigateDocs(url).then((handled)=>{if(!handled)location.href=url.href})});window.addEventListener(\"popstate\",()=>{navigateDocs(new URL(location.href),{replace:true,scroll:false}).then((handled)=>{if(!handled)location.reload()})})};const init=()=>{initToc();initMobileSidebar();initSidebarScroll();initClientNavigation()};if(document.readyState===\"loading\")document.addEventListener(\"DOMContentLoaded\",init,{once:true});else init()})();</script>`;\n}\n\nfunction renderDocsPageActionsRuntimeScript(): string {\n  return `<script>(()=>{if(window.__farmDocsPageActionsRuntime)return;window.__farmDocsPageActionsRuntime=true;const readArticleText=()=>{const article=document.getElementById(\"nd-page\");if(!article)return\"\";const clone=article.cloneNode(true);if(!(clone instanceof HTMLElement))return article.innerText||\"\";clone.querySelectorAll(\"[data-page-actions],.fd-page-footer,.fd-page-nav\").forEach((node)=>node.remove());return clone.innerText||\"\"};const withTitle=(content,format,includeTitle)=>{if(!includeTitle)return content;const title=document.querySelector(\"#nd-page h1\")?.textContent?.trim()||document.title.trim();if(!title)return content;const trimmed=content.trimStart();if(trimmed.startsWith(title)||trimmed.startsWith(\"# \"+title))return content;return format===\"markdown\"?\"# \"+title+\"\\\\n\\\\n\"+content:title+\"\\\\n\\\\n\"+content};const writeClipboard=async(text)=>{if(navigator.clipboard?.writeText){try{await navigator.clipboard.writeText(text);return}catch{}}const textarea=document.createElement(\"textarea\");textarea.value=text;textarea.setAttribute(\"readonly\",\"\");textarea.style.position=\"fixed\";textarea.style.opacity=\"0\";textarea.style.pointerEvents=\"none\";document.body.appendChild(textarea);textarea.select();document.execCommand(\"copy\");textarea.remove()};const markCopied=(button)=>{const label=button.querySelector(\"[data-page-action-label]\");button.dataset.copied=\"true\";button.setAttribute(\"aria-label\",button.dataset.copiedLabel||\"Copied!\");button.title=button.dataset.copiedLabel||\"Copied!\";if(label)label.textContent=button.dataset.copiedLabel||\"Copied!\";const previous=Number(button.dataset.copyTimeout||0);if(previous)clearTimeout(previous);button.dataset.copyTimeout=String(setTimeout(()=>{button.dataset.copied=\"false\";button.setAttribute(\"aria-label\",button.dataset.copyLabel||\"Copy page\");button.title=button.dataset.copyLabel||\"Copy page\";if(label)label.textContent=button.dataset.copyLabel||\"Copy page\";button.dataset.copyTimeout=\"0\"},4500))};document.addEventListener(\"click\",async(event)=>{const target=event.target instanceof Element?event.target.closest('[data-page-action=\"copy-markdown\"]'):null;if(!(target instanceof HTMLButtonElement))return;event.preventDefault();const format=target.dataset.copyMarkdownFormat===\"text\"?\"text\":\"markdown\";const includeTitle=target.dataset.copyMarkdownIncludeTitle===\"true\";let content=\"\";target.disabled=true;try{if(format===\"markdown\"&&target.dataset.markdownUrl){try{const response=await fetch(target.dataset.markdownUrl,{headers:{Accept:\"text/markdown\"}});if(response.ok)content=await response.text()}catch{}}if(!content)content=readArticleText();content=withTitle(content,format,includeTitle);if(content.trim()){await writeClipboard(content);markCopied(target)}}finally{target.disabled=false}})})();</script>`;\n}\n\nfunction renderDocsHashRuntimeScript(): string {\n  return `<script>(()=>{if(window.__farmDocsHashRuntime)return;window.__farmDocsHashRuntime=true;const scrollToHash=()=>{if(!location.hash)return;let id=location.hash.slice(1);try{id=decodeURIComponent(id)}catch{}document.getElementById(id)?.scrollIntoView({block:\"start\"})};const schedule=()=>requestAnimationFrame(()=>requestAnimationFrame(scrollToHash));if(document.readyState===\"loading\")document.addEventListener(\"DOMContentLoaded\",schedule,{once:true});else schedule();window.addEventListener(\"load\",schedule,{once:true});window.addEventListener(\"hashchange\",schedule)})();</script>`;\n}\n\nfunction renderDocsRuntimeScripts(docs: FarmDocsResolvedConfig): string {\n  return `${renderDocsRuntimeScript(docs)}\n${renderDocsHashRuntimeScript()}\n${renderDocsPageActionsRuntimeScript()}`;\n}\n\nfunction renderFarmDocsFontPreloads(fontAssets: readonly FarmDocsPublicFontAsset[]): string {\n  return fontAssets\n    .map(\n      ({ url }) =>\n        `<link rel=\"preload\" href=\"${escapeAttribute(url)}\" as=\"font\" type=\"font/woff2\" crossorigin>`,\n    )\n    .join(\"\\n  \");\n}\n\nfunction renderFarmDocsFontPreloadHeader(fontAssets: readonly FarmDocsPublicFontAsset[]): string {\n  return fontAssets\n    .map(({ url }) => `<${url}>; rel=preload; as=font; type=font/woff2; crossorigin`)\n    .join(\", \");\n}\n\nfunction getFarmLayoutFontPreloads(layoutFonts?: FarmLayoutFonts) {\n  const seen = new Set<string>();\n  return [layoutFonts?.body, layoutFonts?.code].flatMap((font) =>\n    (font?.preloads || []).filter(({ href }) => {\n      if (seen.has(href)) return false;\n      seen.add(href);\n      return true;\n    }),\n  );\n}\n\nfunction renderFarmLayoutFontPreloadHeader(layoutFonts?: FarmLayoutFonts): string {\n  return getFarmLayoutFontPreloads(layoutFonts)\n    .map(({ href, type }) => `<${href}>; rel=preload; as=font; type=${type}; crossorigin`)\n    .join(\", \");\n}\n\nfunction renderPixelDocsHtml(\n  page: LoadedFarmDocsPage,\n  pages: FarmDocsPage[],\n  docs: FarmDocsResolvedConfig,\n  clientEntry: string,\n  faviconHref: string,\n  requestUrl: URL,\n  fontAssets: readonly FarmDocsPublicFontAsset[],\n  fontStylesheetHref?: string,\n  globalStylesheetHref?: string,\n): string {\n  const navTitle =\n    typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n      ? String((docs.config.nav as { title?: unknown }).title || \"Docs\")\n      : \"Docs\";\n  const description = page.description || docs.config.metadata?.description || \"\";\n  // Rendering and TOC extraction share the same preprocessed Marked pass. This\n  // guarantees MDX lines removed before rendering, Setext/CommonMark edge\n  // cases, and duplicate-slug counters cannot diverge between the article and\n  // its navigation.\n  const renderedMarkdown = renderMarkdownDocument(page.body, getThemeTocDepth(docs));\n  const tocItems = renderedMarkdown.tocItems;\n  const themeName = getThemeName(docs);\n  const searchEnabled = isFarmDocsSearchEnabled(docs);\n  const socialMetadata = isFarmDocsSocialImageEnabled(page, docs)\n    ? renderFarmDocsSocialMetadata(\n        createFarmDocsSocialImageDescriptor(page, docs, requestUrl),\n        getFarmDocsCustomSocialImage(page),\n      )\n    : \"\";\n\n  return `<!DOCTYPE html>\n<html class=\"dark\" lang=\"en\" data-docs-theme=\"${escapeAttribute(themeName)}\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"generator\" content=\"@farming-labs/docs via Farm.js\">\n  <title>${escapeHtml(page.title)}</title>\n  ${renderFarmDocsFaviconLink(faviconHref)}\n  ${renderFarmDocsFontPreloads(fontAssets)}\n  ${fontStylesheetHref ? `<link rel=\"stylesheet\" href=\"${escapeAttribute(fontStylesheetHref)}\">` : \"\"}\n  ${globalStylesheetHref ? `<link rel=\"stylesheet\" href=\"${escapeAttribute(globalStylesheetHref)}\">` : \"\"}\n  ${description ? `<meta name=\"description\" content=\"${escapeHtml(description)}\">` : \"\"}\n  ${socialMetadata}\n  ${searchEnabled ? renderDocsSearchBootstrapScript() : \"\"}\n</head>\n<body>\n  <div id=\"nd-docs-layout\" class=\"fd-layout\" data-fd-framework=\"farmjs\">\n    <header class=\"mobile-topbar fd-header\" aria-label=\"Mobile docs navigation\">\n      <button class=\"fd-mobile-nav-btn fd-menu-btn\" type=\"button\" data-sidebar-toggle aria-controls=\"nd-sidebar\" aria-expanded=\"false\" aria-label=\"Open menu\">\n        <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><line x1=\"3\" y1=\"6\" x2=\"21\" y2=\"6\"></line><line x1=\"3\" y1=\"12\" x2=\"21\" y2=\"12\"></line><line x1=\"3\" y1=\"18\" x2=\"21\" y2=\"18\"></line></svg>\n      </button>\n      <a class=\"fd-header-title\" href=\"/\">${escapeHtml(navTitle)}</a>\n      <div class=\"mobile-topbar-actions\">\n        ${searchEnabled ? renderDocsSearchTrigger(true, \"fd-search-trigger-mobile\") : \"\"}\n        <a class=\"mobile-topbar-link\" href=\"/llms.txt\">llms.txt</a>\n      </div>\n    </header>\n    <aside id=\"nd-sidebar\" class=\"fd-sidebar\">\n      <div class=\"sidebar-brand fd-sidebar-header\">\n        <a class=\"fd-sidebar-title\" href=\"/\">${renderFarmDocsBrandMark()}${renderFarmDocsBrandTitle(navTitle)}</a>\n        <span>/ docs</span>\n      </div>\n      ${searchEnabled ? `<div class=\"fd-sidebar-search\">${renderDocsSearchTrigger(true, \"fd-sidebar-search-btn\")}</div>` : \"\"}\n      ${renderPixelNavItems(pages, page.href, docs)}\n    </aside>\n    <div class=\"sidebar-backdrop fd-sidebar-overlay\" data-sidebar-backdrop></div>\n    <main class=\"fd-main\">\n      <div class=\"fd-page\">\n      <article id=\"nd-page\" class=\"prose fd-page-article fd-page-body fd-docs-content\">\n        ${renderPixelBreadcrumb(page, docs)}\n${renderMarkdownHtmlWithTitleMeta(page, docs, renderedMarkdown.html)}\n        ${renderPixelPageFooter(page, docs)}\n        ${renderPixelPageNav(pages, page.href, docs)}\n      </article>\n      <nav id=\"nd-toc\" class=\"fd-toc sticky top-(--fd-docs-row-1) h-[calc(var(--fd-docs-height)-var(--fd-docs-row-1))] flex flex-col [grid-area:toc] w-(--fd-toc-width) pt-12 pe-4 pb-2 max-xl:hidden\" data-toc aria-labelledby=\"toc-title\">\n      <div class=\"fd-toc-inner\">\n        <h3 id=\"toc-title\" class=\"fd-toc-title inline-flex items-center gap-1.5 text-sm text-fd-muted-foreground\"><svg class=\"size-4\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 7h16\"></path><path d=\"M4 12h16\"></path><path d=\"M4 17h16\"></path></svg>On this page</h3>\n        <div class=\"toc-scroll\">\n          ${renderPixelToc(tocItems)}\n        </div>\n      </div>\n    </nav>\n      </div>\n    </main>\n  </div>\n  ${searchEnabled ? renderDocsSearchMount(clientEntry) : \"\"}\n  ${renderDocsRuntimeScripts(docs)}\n</body>\n</html>`;\n}\n\nexport function createFarmDocsHandler(\n  docs: FarmDocsResolvedConfig | undefined,\n  options: FarmDocsHandlerOptions,\n) {\n  const faviconHref = resolveFarmDocsFavicon(docs, options);\n  const fontAssets =\n    options.fontAssets ?? toFarmDocsPublicFontAssets(resolveFarmDocsFontAssets(options.root));\n  const fallbackFontPreloadHeader = renderFarmDocsFontPreloadHeader(fontAssets);\n\n  return async function handleFarmDocsRequest(request: Request): Promise<Response | null> {\n    if (!docs?.enabled || (request.method !== \"GET\" && request.method !== \"HEAD\")) return null;\n\n    const contentDir = resolveFarmDocsContentDir(docs, options);\n    const requestUrl = new URL(request.url);\n    const socialImageSlug = getFarmDocsSocialImageSlug(docs, requestUrl);\n    if (socialImageSlug !== null) {\n      const socialImagePage = loadFarmDocsPage(contentDir, docs, socialImageSlug);\n      if (\n        !socialImagePage ||\n        !isFarmDocsSocialImageEnabled(socialImagePage, docs) ||\n        getFarmDocsCustomSocialImage(socialImagePage)\n      ) {\n        return null;\n      }\n\n      const descriptor = createFarmDocsSocialImageDescriptor(socialImagePage, docs, requestUrl);\n      if (requestUrl.pathname !== descriptor.imagePath) return null;\n\n      const etag = `\"${descriptor.hash}\"`;\n      const immutable = requestUrl.searchParams.get(\"v\") === descriptor.hash;\n      const headers = new Headers({\n        \"Content-Type\": \"image/svg+xml; charset=utf-8\",\n        \"Cache-Control\": immutable\n          ? \"public, max-age=31536000, immutable\"\n          : \"public, max-age=0, must-revalidate\",\n        ETag: etag,\n        \"X-Content-Type-Options\": \"nosniff\",\n      });\n      if (matchesFarmIfNoneMatch(request.headers.get(\"if-none-match\"), etag)) {\n        return new Response(null, { status: 304, headers });\n      }\n      if (request.method === \"HEAD\") return new Response(null, { status: 200, headers });\n\n      return new Response(renderFarmDocsSocialImageSvg(descriptor), { status: 200, headers });\n    }\n\n    const publicResponse = createFarmDocsPublicResponse(contentDir, docs, request);\n    if (publicResponse) return omitFarmDocsHeadBody(request, publicResponse);\n\n    if (!isFarmDocsRequest(docs, request)) return null;\n\n    const page = loadPage(contentDir, docs, request);\n    if (!page) return null;\n\n    if (shouldReturnMarkdown(request)) {\n      const origin = new URL(request.url).origin;\n      return omitFarmDocsHeadBody(\n        request,\n        new Response(\n          renderDocsMarkdownDocument(toFarmDocsMarkdownPage(page), {\n            origin,\n            llms: docs.config.llmsTxt ?? true,\n            sitemap: docs.config.sitemap,\n          }),\n          {\n            status: 200,\n            headers: {\n              \"Content-Type\": \"text/markdown; charset=utf-8\",\n              \"Cache-Control\": \"public, max-age=60\",\n            },\n          },\n        ),\n      );\n    }\n\n    const pathname = new URL(request.url).pathname;\n    const layoutFonts = await options.resolveLayoutFonts?.(pathname);\n    const usesLayoutFonts = Boolean(layoutFonts?.body || layoutFonts?.code);\n    const activeFontAssets = usesLayoutFonts ? [] : fontAssets;\n    const fontPreloadHeader = usesLayoutFonts\n      ? renderFarmLayoutFontPreloadHeader(layoutFonts)\n      : fallbackFontPreloadHeader;\n\n    return omitFarmDocsHeadBody(\n      request,\n      new Response(\n        renderPixelDocsHtml(\n          page,\n          discoverFarmDocsPages(contentDir, docs),\n          docs,\n          options.clientEntry || \"/farm-client.js\",\n          faviconHref,\n          requestUrl,\n          activeFontAssets,\n          usesLayoutFonts ? options.fontStylesheetHref : undefined,\n          options.globalStylesheetHref,\n        ),\n        {\n          status: 200,\n          headers: {\n            \"Content-Type\": \"text/html; charset=utf-8\",\n            \"Cache-Control\": \"public, s-maxage=60, stale-while-revalidate=300\",\n            ...(fontPreloadHeader ? { Link: fontPreloadHeader } : {}),\n          },\n        },\n      ),\n    );\n  };\n}\n","export const FARM_NAVIGATION_HEAD_SELECTOR = [\n  \"meta[name]\",\n  \"meta[property]\",\n  \"meta[http-equiv]\",\n  \"meta[charset]\",\n  \"meta[itemprop]\",\n  'link[rel~=\"author\"]',\n  'link[rel~=\"canonical\"]',\n  'link[rel~=\"alternate\"]',\n  'link[rel~=\"icon\"]',\n  'link[rel~=\"apple-touch-icon\"]',\n  'link[rel~=\"manifest\"]',\n  'link[rel~=\"search\"]',\n  'link[rel~=\"next\"]',\n  'link[rel~=\"prev\"]',\n  'link[rel~=\"publisher\"]',\n  'link[rel~=\"license\"]',\n  'link[rel~=\"help\"]',\n  'link[rel~=\"me\"]',\n  'link[rel~=\"pingback\"]',\n  'link[rel~=\"privacy-policy\"]',\n  'link[rel~=\"terms-of-service\"]',\n].join(\",\");\n\nexport function reconcileFarmDocumentHead(nextDocument: Document): void {\n  const nextTitle = nextDocument.querySelector(\"title\");\n  document.title = nextTitle?.textContent || \"\";\n\n  document.head.querySelectorAll(FARM_NAVIGATION_HEAD_SELECTOR).forEach((node) => node.remove());\n  nextDocument.head\n    .querySelectorAll(FARM_NAVIGATION_HEAD_SELECTOR)\n    .forEach((node) => document.head.appendChild(document.importNode(node, true)));\n}\n","export type FarmMarkdownRouteInput =\n  | string\n  | {\n      route: string;\n      title?: string;\n      cache?: number | false;\n    };\n\nexport interface FarmMarkdownUserConfig {\n  /**\n   * Enable generated markdown representations for React pages.\n   * @default true\n   */\n  enabled?: boolean;\n  /**\n   * Routes that may expose generated markdown. Every page is exposed by default.\n   */\n  expose?: boolean | FarmMarkdownRouteInput[];\n  /** @deprecated Use `expose`. */\n  routes?: FarmMarkdownRouteInput[];\n  cache?: number | false;\n  includeMetadata?: boolean;\n}\n\nexport interface FarmMarkdownResolvedRoute {\n  route: string;\n  title?: string;\n  cache?: number | false;\n}\n\nexport interface FarmMarkdownResolvedConfig {\n  enabled: boolean;\n  expose: true | FarmMarkdownResolvedRoute[];\n  cache: number | false;\n  includeMetadata: boolean;\n}\n\nexport interface FarmMarkdownMirrorTarget {\n  pathname: string;\n  route: FarmMarkdownResolvedRoute | null;\n}\n\nexport interface ResolveMarkdownMirrorTargetOptions {\n  accept?: string | null;\n}\n\nexport interface CreateMarkdownMirrorResponseOptions {\n  request: Request;\n  config?: FarmMarkdownResolvedConfig;\n  routeExists?: (pathname: string) => boolean;\n  renderPage: (request: Request) => Response | Promise<Response>;\n}\n\nexport interface ApplyMarkdownNegotiationHeadersOptions {\n  config?: FarmMarkdownResolvedConfig;\n  pathname: string;\n}\n\nexport function resolveMarkdownConfig(\n  config: FarmMarkdownUserConfig | boolean | undefined,\n): FarmMarkdownResolvedConfig {\n  if (config === false) {\n    return {\n      enabled: false,\n      expose: [],\n      cache: false,\n      includeMetadata: true,\n    };\n  }\n\n  if (config === true || config === undefined) {\n    return {\n      enabled: true,\n      expose: true,\n      cache: false,\n      includeMetadata: true,\n    };\n  }\n\n  const exposeInput = config.expose ?? config.routes ?? true;\n  const expose =\n    exposeInput === true\n      ? true\n      : Array.isArray(exposeInput)\n        ? exposeInput.map(normalizeMarkdownRouteInput)\n        : [];\n\n  return {\n    enabled: config.enabled !== false && (expose === true || expose.length > 0),\n    expose,\n    cache: config.cache ?? false,\n    includeMetadata: config.includeMetadata ?? true,\n  };\n}\n\nexport function resolveMarkdownMirrorTarget(\n  config: FarmMarkdownResolvedConfig | undefined,\n  pathname: string,\n  options: ResolveMarkdownMirrorTargetOptions = {},\n): FarmMarkdownMirrorTarget | null {\n  const hasMarkdownExtension = pathname.toLowerCase().endsWith(\".md\");\n  if (!config?.enabled || (!hasMarkdownExtension && !requestAcceptsMarkdown(options.accept))) {\n    return null;\n  }\n\n  const targetPathname = normalizeMarkdownRoute(\n    hasMarkdownExtension ? pathname.slice(0, -\".md\".length) || \"/\" : pathname,\n  );\n  const route = findExposedMarkdownRoute(config, targetPathname);\n  if (!route && config.expose !== true) {\n    return null;\n  }\n\n  return {\n    pathname: targetPathname,\n    route,\n  };\n}\n\nexport async function createMarkdownMirrorResponse(\n  options: CreateMarkdownMirrorResponseOptions,\n): Promise<Response | null> {\n  if (options.request.method !== \"GET\" && options.request.method !== \"HEAD\") {\n    return null;\n  }\n\n  const requestUrl = new URL(options.request.url);\n  const hasMarkdownExtension = requestUrl.pathname.toLowerCase().endsWith(\".md\");\n  const target = resolveMarkdownMirrorTarget(options.config, requestUrl.pathname, {\n    accept: options.request.headers.get(\"accept\"),\n  });\n  if (!target) {\n    return null;\n  }\n\n  if (options.routeExists && !options.routeExists(target.pathname)) {\n    return null;\n  }\n\n  const pageUrl = new URL(options.request.url);\n  pageUrl.pathname = target.pathname;\n  const headers = new Headers(options.request.headers);\n  headers.set(\"accept\", \"text/html\");\n\n  const pageResponse = await options.renderPage(\n    new Request(pageUrl, {\n      method: \"GET\",\n      headers,\n    }),\n  );\n\n  if (!isHtmlResponse(pageResponse)) {\n    return null;\n  }\n\n  const html = await pageResponse.text();\n  const markdown = htmlToMarkdown(html, {\n    title: target.route?.title,\n    includeMetadata: options.config?.includeMetadata ?? true,\n    sourcePath: target.pathname,\n  });\n  const headersOut = new Headers({\n    \"Content-Type\": \"text/markdown; charset=utf-8\",\n    \"Content-Location\": target.pathname === \"/\" ? \"/index.md\" : `${target.pathname}.md`,\n    \"X-Farm-Markdown-Route\": target.pathname,\n  });\n  if (!hasMarkdownExtension) {\n    headersOut.set(\"Vary\", \"Accept\");\n  }\n  const cache = target.route?.cache ?? options.config?.cache ?? false;\n  headersOut.set(\"Cache-Control\", createMarkdownCacheHeader(cache));\n\n  return new Response(options.request.method === \"HEAD\" ? null : markdown, {\n    status: pageResponse.status,\n    headers: headersOut,\n  });\n}\n\nexport function applyMarkdownNegotiationHeaders(\n  response: Response,\n  options: ApplyMarkdownNegotiationHeadersOptions,\n): Response {\n  if (!isHtmlResponse(response)) {\n    return response;\n  }\n\n  const target = resolveMarkdownMirrorTarget(options.config, options.pathname, {\n    accept: \"text/markdown\",\n  });\n  if (!target) {\n    return response;\n  }\n\n  const alternatePath = getMarkdownAlternatePath(target.pathname);\n  const headers = new Headers(response.headers);\n  appendHeaderToken(headers, \"Vary\", \"Accept\");\n  headers.append(\"Link\", `<${alternatePath}>; rel=\"alternate\"; type=\"text/markdown\"`);\n\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function htmlToMarkdown(\n  html: string,\n  options: {\n    title?: string;\n    sourcePath?: string;\n    includeMetadata?: boolean;\n  } = {},\n): string {\n  const title = options.title ?? extractHtmlTitle(html);\n  let source = extractHtmlBody(html)\n    .replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \"\")\n    .replace(/<style\\b[^>]*>[\\s\\S]*?<\\/style>/gi, \"\")\n    .replace(/<noscript\\b[^>]*>[\\s\\S]*?<\\/noscript>/gi, \"\")\n    .replace(/<!--[\\s\\S]*?-->/g, \"\");\n\n  source = source.replace(/<pre\\b[^>]*><code\\b[^>]*>([\\s\\S]*?)<\\/code><\\/pre>/gi, (_, code) => {\n    return `\\n\\n\\`\\`\\`\\n${decodeHtml(stripTags(code)).trim()}\\n\\`\\`\\`\\n\\n`;\n  });\n  source = source.replace(/<pre\\b[^>]*>([\\s\\S]*?)<\\/pre>/gi, (_, code) => {\n    return `\\n\\n\\`\\`\\`\\n${decodeHtml(stripTags(code)).trim()}\\n\\`\\`\\`\\n\\n`;\n  });\n  source = source.replace(/<h([1-6])\\b[^>]*>([\\s\\S]*?)<\\/h\\1>/gi, (_, level, content) => {\n    return `\\n\\n${\"#\".repeat(Number(level))} ${toInlineMarkdown(content).trim()}\\n\\n`;\n  });\n  source = source.replace(/<p\\b[^>]*>([\\s\\S]*?)<\\/p>/gi, (_, content) => {\n    return `\\n\\n${toInlineMarkdown(content).trim()}\\n\\n`;\n  });\n  source = source.replace(/<blockquote\\b[^>]*>([\\s\\S]*?)<\\/blockquote>/gi, (_, content) => {\n    const quote = htmlToMarkdown(content, { includeMetadata: false })\n      .split(\"\\n\")\n      .filter((line) => line.trim().length > 0)\n      .map((line) => `> ${line}`)\n      .join(\"\\n\");\n    return `\\n\\n${quote}\\n\\n`;\n  });\n  source = source.replace(/<li\\b[^>]*>([\\s\\S]*?)<\\/li>/gi, (_, content) => {\n    return `\\n- ${toInlineMarkdown(content).trim()}`;\n  });\n  source = source\n    .replace(/<\\/?(ul|ol|main|section|article|header|footer|nav|aside|div)\\b[^>]*>/gi, \"\\n\")\n    .replace(/<br\\s*\\/?>/gi, \"\\n\")\n    .replace(/<hr\\s*\\/?>/gi, \"\\n\\n---\\n\\n\");\n\n  let markdown = stripTags(source)\n    .split(\"\\n\")\n    .map((line) => line.replace(/[ \\t]+$/g, \"\"))\n    .join(\"\\n\")\n    .replace(/\\n{3,}/g, \"\\n\\n\")\n    .trim();\n\n  if (options.includeMetadata !== false) {\n    const metadata: string[] = [];\n    if (title && !markdown.startsWith(\"# \")) {\n      metadata.push(`# ${title}`);\n    }\n    if (options.sourcePath) {\n      metadata.push(`Source: ${options.sourcePath}`);\n    }\n    if (metadata.length) {\n      markdown = `${metadata.join(\"\\n\\n\")}${markdown ? `\\n\\n${markdown}` : \"\"}`;\n    }\n  }\n\n  return `${markdown}\\n`;\n}\n\nfunction normalizeMarkdownRouteInput(input: FarmMarkdownRouteInput): FarmMarkdownResolvedRoute {\n  if (typeof input === \"string\") {\n    return {\n      route: normalizeMarkdownRoute(input),\n    };\n  }\n\n  return {\n    ...input,\n    route: normalizeMarkdownRoute(input.route),\n  };\n}\n\nfunction normalizeMarkdownRoute(route: string): string {\n  const withoutMarkdownExtension = route.toLowerCase().endsWith(\".md\") ? route.slice(0, -3) : route;\n  const withSlash = withoutMarkdownExtension.startsWith(\"/\")\n    ? withoutMarkdownExtension\n    : `/${withoutMarkdownExtension}`;\n  const normalized = withSlash.replace(/\\/+/g, \"/\").replace(/\\/$/g, \"\");\n  return normalized === \"\" || normalized === \"/index\" ? \"/\" : normalized;\n}\n\n/**\n * Quality value an `Accept` header assigns a media type, or 0 when the client\n * will not take it.\n *\n * `q=0` means \"not acceptable\" per RFC 9110, so it has to be distinguished from\n * an absent entry rather than treated as a match. Wildcards are opt-in: a client\n * sending `*&#47;*` will take anything, which says nothing about whether it would\n * rather have Markdown than HTML, so callers negotiating between two concrete\n * types should ask for exact entries only.\n */\nexport function farmAcceptQuality(\n  accept: string | null | undefined,\n  mediaType: string,\n  options: { wildcards?: boolean } = {},\n): number {\n  if (!accept) return 0;\n  const target = mediaType.toLowerCase();\n  const [targetType] = target.split(\"/\");\n  let best = 0;\n\n  for (const entry of accept.split(\",\")) {\n    const [candidate, ...parameters] = entry\n      .trim()\n      .toLowerCase()\n      .split(\";\")\n      .map((part) => part.trim());\n    if (!candidate) continue;\n\n    const matches =\n      candidate === target ||\n      (options.wildcards === true && (candidate === \"*/*\" || candidate === `${targetType}/*`));\n    if (!matches) continue;\n\n    const quality = parameters.find((parameter) => parameter.startsWith(\"q=\"));\n    const value = quality === undefined ? 1 : Number(quality.slice(2));\n    if (!Number.isFinite(value) || value <= 0) continue;\n    if (value > best) best = value;\n  }\n\n  return best;\n}\n\nexport function requestAcceptsMarkdown(accept: string | null | undefined): boolean {\n  if (!accept) {\n    return false;\n  }\n\n  return accept.split(\",\").some((entry) => {\n    const [mediaType, ...parameters] = entry\n      .trim()\n      .toLowerCase()\n      .split(\";\")\n      .map((part) => part.trim());\n    if (mediaType !== \"text/markdown\") {\n      return false;\n    }\n\n    const quality = parameters.find((parameter) => parameter.startsWith(\"q=\"));\n    return quality === undefined || Number(quality.slice(2)) > 0;\n  });\n}\n\nfunction getMarkdownAlternatePath(pathname: string): string {\n  return pathname === \"/\" ? \"/index.md\" : `${pathname}.md`;\n}\n\nfunction appendHeaderToken(headers: Headers, name: string, token: string): void {\n  const current = headers.get(name);\n  if (!current) {\n    headers.set(name, token);\n    return;\n  }\n\n  const tokens = current.split(\",\").map((value) => value.trim().toLowerCase());\n  if (!tokens.includes(token.toLowerCase())) {\n    headers.set(name, `${current}, ${token}`);\n  }\n}\n\nfunction findExposedMarkdownRoute(\n  config: FarmMarkdownResolvedConfig,\n  pathname: string,\n): FarmMarkdownResolvedRoute | null {\n  if (config.expose === true) {\n    return null;\n  }\n\n  return config.expose.find((route) => routeMatches(route.route, pathname)) ?? null;\n}\n\nfunction routeMatches(pattern: string, pathname: string): boolean {\n  if (pattern === pathname) {\n    return true;\n  }\n\n  const escaped = pattern\n    .split(\"/\")\n    .map((segment) => {\n      if (/^\\[\\.\\.\\.[^\\]]+\\]$/.test(segment)) {\n        return \".*\";\n      }\n      if (/^\\[[^\\]]+\\]$/.test(segment)) {\n        return \"[^/]+\";\n      }\n      return segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n    })\n    .join(\"/\");\n\n  return new RegExp(`^${escaped}$`).test(pathname);\n}\n\nfunction isHtmlResponse(response: Response): boolean {\n  const contentType = response.headers.get(\"content-type\") ?? \"\";\n  return contentType.includes(\"text/html\");\n}\n\nfunction createMarkdownCacheHeader(cache: number | false): string {\n  if (cache === false || cache <= 0) {\n    return \"no-store\";\n  }\n\n  return `public, max-age=${cache}, s-maxage=${cache}`;\n}\n\nfunction extractHtmlTitle(html: string): string | undefined {\n  const match = html.match(/<title\\b[^>]*>([\\s\\S]*?)<\\/title>/i);\n  return match ? decodeHtml(stripTags(match[1])).trim() : undefined;\n}\n\nfunction extractHtmlBody(html: string): string {\n  const rootMatch = html.match(\n    /<div\\b[^>]*id=[\"']root[\"'][^>]*>([\\s\\S]*?)<\\/div>\\s*(?:<script|<\\/body>|$)/i,\n  );\n  const bodyMatch = html.match(/<body\\b[^>]*>([\\s\\S]*?)<\\/body>/i);\n  const body = rootMatch ? rootMatch[1] : bodyMatch ? bodyMatch[1] : html;\n  return extractFirstElementContent(body, [\"main\", \"article\"]) ?? body;\n}\n\nfunction extractFirstElementContent(html: string, tagNames: string[]): string | undefined {\n  for (const tagName of tagNames) {\n    const match = html.match(new RegExp(`<${tagName}\\\\b[^>]*>([\\\\s\\\\S]*?)<\\\\/${tagName}>`, \"i\"));\n    if (match) {\n      return match[1];\n    }\n  }\n\n  return undefined;\n}\n\nfunction toInlineMarkdown(html: string): string {\n  let source = html\n    .replace(/<a\\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>([\\s\\S]*?)<\\/a>/gi, (_, href, text) => {\n      const label: string = toInlineMarkdown(text).trim() || href;\n      return `[${label}](${decodeHtml(href)})`;\n    })\n    .replace(\n      /<img\\b[^>]*src=[\"']([^\"']+)[\"'][^>]*alt=[\"']([^\"']*)[\"'][^>]*\\/?>/gi,\n      (_, src, alt) => {\n        return `![${decodeHtml(alt)}](${decodeHtml(src)})`;\n      },\n    )\n    .replace(/<strong\\b[^>]*>([\\s\\S]*?)<\\/strong>/gi, (_, content) => {\n      return `**${toInlineMarkdown(content).trim()}**`;\n    })\n    .replace(/<b\\b[^>]*>([\\s\\S]*?)<\\/b>/gi, (_, content) => {\n      return `**${toInlineMarkdown(content).trim()}**`;\n    })\n    .replace(/<em\\b[^>]*>([\\s\\S]*?)<\\/em>/gi, (_, content) => {\n      return `_${toInlineMarkdown(content).trim()}_`;\n    })\n    .replace(/<i\\b[^>]*>([\\s\\S]*?)<\\/i>/gi, (_, content) => {\n      return `_${toInlineMarkdown(content).trim()}_`;\n    })\n    .replace(/<code\\b[^>]*>([\\s\\S]*?)<\\/code>/gi, (_, content) => {\n      return `\\`${decodeHtml(stripTags(content)).trim()}\\``;\n    })\n    .replace(/<br\\s*\\/?>/gi, \"\\n\");\n\n  source = stripTags(source);\n  return decodeHtml(source).replace(/\\s+/g, \" \");\n}\n\nfunction stripTags(input: string): string {\n  return input.replace(/<[^>]+>/g, \"\");\n}\n\nfunction decodeHtml(input: string): string {\n  return input.replace(/&(?:nbsp|amp|lt|gt|quot|#39|#(?:x|X)[0-9a-fA-F]+|#[0-9]+);/g, (entity) => {\n    switch (entity) {\n      case \"&nbsp;\":\n        return \" \";\n      case \"&amp;\":\n        return \"&\";\n      case \"&lt;\":\n        return \"<\";\n      case \"&gt;\":\n        return \">\";\n      case \"&quot;\":\n        return '\"';\n      case \"&#39;\":\n        return \"'\";\n    }\n\n    const hexadecimal = entity[2] === \"x\" || entity[2] === \"X\";\n    const codePoint = Number.parseInt(entity.slice(hexadecimal ? 3 : 2, -1), hexadecimal ? 16 : 10);\n    return codePoint === 0 || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)\n      ? \"\\uFFFD\"\n      : String.fromCodePoint(codePoint);\n  });\n}\n","export type RouteSegmentSpecificity = \"static\" | \"dynamic\" | \"catch-all\" | \"optional-catch-all\";\n\nexport class AmbiguousRouteError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"AmbiguousRouteError\";\n  }\n}\n\nexport class NonTerminalCatchAllRouteError extends TypeError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"NonTerminalCatchAllRouteError\";\n  }\n}\n\nexport class DuplicateRouteParameterError extends AmbiguousRouteError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"DuplicateRouteParameterError\";\n  }\n}\n\nexport class ReservedRouteParameterError extends AmbiguousRouteError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"ReservedRouteParameterError\";\n  }\n}\n\nexport class BrowserUnstableRouteError extends TypeError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"BrowserUnstableRouteError\";\n  }\n}\n\nconst SEGMENT_RANK: Record<RouteSegmentSpecificity, number> = {\n  static: 4,\n  dynamic: 3,\n  \"catch-all\": 1,\n  \"optional-catch-all\": 0,\n};\n\n// Ending a route is more specific than consuming the same path through a\n// catch-all, while a following static or dynamic segment remains more specific.\nconst ROUTE_END_RANK = 2;\n\n/** Sort route patterns from the most specific segment sequence to the least specific. */\nexport function compareRouteSpecificity(\n  left: readonly RouteSegmentSpecificity[],\n  right: readonly RouteSegmentSpecificity[],\n): number {\n  const length = Math.max(left.length, right.length);\n\n  for (let index = 0; index < length; index++) {\n    const leftRank = index < left.length ? SEGMENT_RANK[left[index]!] : ROUTE_END_RANK;\n    const rightRank = index < right.length ? SEGMENT_RANK[right[index]!] : ROUTE_END_RANK;\n    if (leftRank !== rightRank) return rightRank - leftRank;\n  }\n\n  return 0;\n}\n\nexport type RoutePatternSyntax = \"page\" | \"router\" | \"api\";\n\nconst ROUTER_PARAMETER_NAME = \"[A-Za-z0-9_$-]+\";\nconst PAGE_PARAMETER_PATTERN = /^(?:\\[\\[\\.\\.\\.(.+)\\]\\]|\\[\\.\\.\\.(.+)\\]|\\[(.+)\\])$/;\nconst ROUTER_PARAMETER_PATTERN =\n  /^(?:\\[\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]\\]|\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]|\\[([A-Za-z0-9_$-]+)\\]|:([A-Za-z0-9_$-]+)|\\*([A-Za-z0-9_$-]+)\\??)$/;\nconst RESERVED_PARAMETER_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport function assertBrowserStableRoutePath(pattern: string): void {\n  if (pattern.includes(\"\\\\\") || hasControlCharacter(pattern)) {\n    throw new BrowserUnstableRouteError(\n      `Route path \"${pattern}\" cannot contain backslashes or control characters.`,\n    );\n  }\n\n  for (const segment of pattern.split(\"/\").filter(Boolean)) {\n    if (\n      (segment.startsWith(\"(\") && segment.endsWith(\")\")) ||\n      (segment.startsWith(\"[\") && segment.endsWith(\"]\"))\n    ) {\n      continue;\n    }\n\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes stay literal in browser pathnames.\n    }\n    if (\n      decoded === \".\" ||\n      decoded === \"..\" ||\n      decoded.includes(\"/\") ||\n      decoded.includes(\"\\\\\") ||\n      hasControlCharacter(decoded)\n    ) {\n      throw new BrowserUnstableRouteError(\n        `Route path \"${pattern}\" contains browser-unstable segment \"${segment}\".`,\n      );\n    }\n  }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n  return Array.from(value).some((character) => {\n    const code = character.charCodeAt(0);\n    return code <= 31 || (code >= 127 && code <= 159);\n  });\n}\n\nexport function assertUniqueRouteParameters(\n  pattern: string,\n  syntax: RoutePatternSyntax = \"page\",\n): void {\n  const parameterPattern = syntax === \"router\" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;\n  const names = new Set<string>();\n\n  for (const segment of splitRoutePattern(pattern, syntax)) {\n    const match = parameterPattern.exec(segment);\n    const name = match?.slice(1).find(Boolean);\n    if (!name) continue;\n    if (RESERVED_PARAMETER_NAMES.has(name)) {\n      throw new ReservedRouteParameterError(\n        `Route parameter \"${name}\" in route \"${pattern}\" is reserved. Use a different parameter name.`,\n      );\n    }\n    if (names.has(name)) {\n      throw new DuplicateRouteParameterError(\n        `Duplicate route parameter \"${name}\" in route \"${pattern}\". Each dynamic segment must use a unique name.`,\n      );\n    }\n    names.add(name);\n  }\n}\n\nfunction splitRoutePattern(pattern: string, syntax: RoutePatternSyntax): string[] {\n  return pattern\n    .replace(/\\\\/g, \"/\")\n    .split(\"/\")\n    .filter(Boolean)\n    .filter((segment) =>\n      syntax === \"api\" ? true : !(segment.startsWith(\"(\") && segment.endsWith(\")\")),\n    );\n}\n\nexport function assertTerminalCatchAll(pattern: string, syntax: RoutePatternSyntax = \"page\"): void {\n  const segments = splitRoutePattern(pattern, syntax);\n  const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n  const catchAllPattern = new RegExp(\n    syntax === \"router\"\n      ? `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]|\\\\*${parameterName}\\\\??)$`\n      : `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\])$`,\n  );\n  const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));\n  if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {\n    throw new NonTerminalCatchAllRouteError(\n      `Catch-all segment \"${segments[catchAllIndex]}\" must be the final segment in route \"${pattern}\".`,\n    );\n  }\n}\n\n/** Return the URL-matching shape of a route without its parameter names. */\nexport function getRoutePatternShape(pattern: string, syntax: RoutePatternSyntax = \"page\"): string {\n  assertTerminalCatchAll(pattern, syntax);\n  const segments = splitRoutePattern(pattern, syntax).map((segment) => {\n    const specificity = getPatternSegmentSpecificity(segment, syntax);\n    if (specificity !== \"static\") return specificity;\n\n    try {\n      return `static:${decodeURIComponent(segment)}`;\n    } catch {\n      return `static:${segment}`;\n    }\n  });\n\n  return segments.length === 0 ? \"/\" : JSON.stringify(segments);\n}\n\n/** Return the specificity of every URL-consuming segment in a route pattern. */\nexport function getRoutePatternSpecificity(\n  pattern: string,\n  syntax: RoutePatternSyntax = \"page\",\n): RouteSegmentSpecificity[] {\n  assertTerminalCatchAll(pattern, syntax);\n  return splitRoutePattern(pattern, syntax).map((segment) =>\n    getPatternSegmentSpecificity(segment, syntax),\n  );\n}\n\nfunction getPatternSegmentSpecificity(\n  segment: string,\n  syntax: RoutePatternSyntax,\n): RouteSegmentSpecificity {\n  const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n  const supportsColonAndStar = syntax === \"router\";\n  if (\n    new RegExp(`^\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}\\\\?$`).test(segment))\n  ) {\n    return \"optional-catch-all\";\n  }\n  if (\n    new RegExp(`^\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}$`).test(segment))\n  ) {\n    return \"catch-all\";\n  }\n  if (\n    new RegExp(`^\\\\[${parameterName}\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment))\n  ) {\n    return \"dynamic\";\n  }\n\n  return \"static\";\n}\n","import { assertBrowserStableRoutePath } from \"./routing/specificity\";\n\ninterface FarmNodeAbortRequest {\n  aborted?: boolean;\n  once(event: \"aborted\", listener: () => void): unknown;\n  off(event: \"aborted\", listener: () => void): unknown;\n}\n\ninterface FarmNodeAbortResponse {\n  writableEnded: boolean;\n  once(event: \"close\" | \"finish\", listener: () => void): unknown;\n  off(event: \"close\" | \"finish\", listener: () => void): unknown;\n}\n\n/** Share disconnect semantics between development and production Node requests. */\nexport function createFarmNodeRequestAbortSignal(\n  req: FarmNodeAbortRequest,\n  res: FarmNodeAbortResponse,\n): AbortSignal {\n  const controller = new AbortController();\n  let disposed = false;\n  const dispose = () => {\n    if (disposed) return;\n    disposed = true;\n    req.off(\"aborted\", abort);\n    res.off(\"close\", abortOnEarlyClose);\n    res.off(\"finish\", dispose);\n    controller.signal.removeEventListener(\"abort\", dispose);\n  };\n  const abort = () => controller.abort();\n  const abortOnEarlyClose = () => {\n    if (!res.writableEnded) abort();\n    dispose();\n  };\n\n  if (req.aborted) {\n    controller.abort();\n    return controller.signal;\n  }\n\n  req.once(\"aborted\", abort);\n  res.once(\"close\", abortOnEarlyClose);\n  res.once(\"finish\", dispose);\n  controller.signal.addEventListener(\"abort\", dispose, { once: true });\n  return controller.signal;\n}\n\nexport const DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 10_000_000;\nexport const DEFAULT_FARM_SERVER_HEADERS_TIMEOUT = 60_000;\nexport const DEFAULT_FARM_SERVER_REQUEST_TIMEOUT = 300_000;\nexport const DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT = 5_000;\nexport const DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT = 30_000;\nconst MAX_FARM_SERVER_TIMEOUT = 2_147_483_647;\n\nexport type FarmServerDuration = number | `${number}${\"ms\" | \"s\" | \"m\" | \"h\"}`;\n\nexport interface FarmServerHealthConfig {\n  /** Liveness endpoint. It remains healthy while a production process drains. */\n  livenessPath?: string;\n  /** Readiness endpoint. It returns 503 until startup completes and while draining. */\n  readinessPath?: string;\n}\n\nexport interface ResolvedFarmServerHealthConfig {\n  enabled: boolean;\n  livenessPath: string;\n  readinessPath: string;\n}\n\nexport interface FarmServerConfig {\n  /** Maximum request body size for API routes, integrations, workflows, and uploads. */\n  bodySizeLimit?: number | string;\n  /** Trust proxy-provided client address and request authority headers. Enable only behind a trusted proxy. */\n  trustProxy?: boolean;\n  /** Maximum time for a Node client to send complete request headers. */\n  headersTimeout?: FarmServerDuration;\n  /** Maximum time for a Node client to send the complete request. */\n  requestTimeout?: FarmServerDuration;\n  /** How long an idle Node keep-alive connection remains open after a response. */\n  keepAliveTimeout?: FarmServerDuration;\n  /** Maximum time the Node adapter drains traffic before forcing shutdown. */\n  gracefulShutdownTimeout?: FarmServerDuration;\n  /** Production liveness and readiness endpoints. Set to false to disable them. */\n  health?: false | FarmServerHealthConfig;\n}\n\nexport interface ResolvedFarmServerConfig {\n  bodySizeLimit: number;\n  trustProxy: boolean;\n  headersTimeout: number;\n  requestTimeout: number;\n  keepAliveTimeout: number;\n  gracefulShutdownTimeout: number;\n  health: ResolvedFarmServerHealthConfig;\n}\n\nexport type FarmRequestBodyErrorCode = \"BODY_TOO_LARGE\" | \"INVALID_CONTENT_LENGTH\";\n\n/** Apply the weak entity-tag comparison required by If-None-Match. */\nexport function matchesFarmIfNoneMatch(\n  value: string | readonly string[] | null | undefined,\n  etag: string,\n): boolean {\n  const expected = parseEntityTag(trimOptionalWhitespace(etag));\n  if (!expected) return false;\n\n  const values = Array.isArray(value) ? value : [value];\n  const combined = values\n    .filter((header): header is string => typeof header === \"string\")\n    .join(\",\");\n  const fieldValue = trimOptionalWhitespace(combined);\n  if (!fieldValue) return false;\n  if (fieldValue === \"*\") return true;\n\n  let matched = false;\n  let hasEntityTag = false;\n  for (const candidate of splitEntityTags(fieldValue)) {\n    const token = trimOptionalWhitespace(candidate);\n    if (!token) continue;\n\n    const parsed = parseEntityTag(token);\n    if (!parsed) return false;\n    hasEntityTag = true;\n    if (parsed === expected) matched = true;\n  }\n\n  return hasEntityTag && matched;\n}\n\nfunction trimOptionalWhitespace(value: string): string {\n  return value.replace(/^[\\t ]+|[\\t ]+$/g, \"\");\n}\n\nfunction parseEntityTag(value: string): string | null {\n  const opaqueTag = value.startsWith(\"W/\") ? value.slice(2) : value;\n  if (opaqueTag.length < 2 || opaqueTag[0] !== '\"' || opaqueTag.at(-1) !== '\"') return null;\n\n  for (let index = 1; index < opaqueTag.length - 1; index++) {\n    const code = opaqueTag.charCodeAt(index);\n    if (code === 0x21 || (code >= 0x23 && code <= 0x7e) || code >= 0x80) continue;\n    return null;\n  }\n\n  return opaqueTag;\n}\n\nfunction splitEntityTags(value: string): string[] {\n  const tags: string[] = [];\n  let start = 0;\n  let quoted = false;\n\n  for (let index = 0; index < value.length; index++) {\n    const character = value[index];\n    if (character === '\"') {\n      quoted = !quoted;\n    } else if (character === \",\" && !quoted) {\n      tags.push(value.slice(start, index));\n      start = index + 1;\n    }\n  }\n\n  tags.push(value.slice(start));\n  return tags;\n}\n\nexport class FarmRequestBodyError extends Error {\n  readonly code: FarmRequestBodyErrorCode;\n  readonly status: number;\n\n  constructor(code: FarmRequestBodyErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"FarmRequestBodyError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\nexport function resolveFarmServerConfig(\n  config: FarmServerConfig | ResolvedFarmServerConfig | undefined,\n): ResolvedFarmServerConfig {\n  const headersTimeout = parseFarmServerDuration(\n    config?.headersTimeout ?? DEFAULT_FARM_SERVER_HEADERS_TIMEOUT,\n    \"server.headersTimeout\",\n  );\n  const requestTimeout = parseFarmServerDuration(\n    config?.requestTimeout ?? DEFAULT_FARM_SERVER_REQUEST_TIMEOUT,\n    \"server.requestTimeout\",\n  );\n  if (headersTimeout > requestTimeout) {\n    throw new TypeError(\"server.headersTimeout must not exceed server.requestTimeout\");\n  }\n\n  return Object.freeze({\n    bodySizeLimit: parseBodySizeLimit(\n      config?.bodySizeLimit ?? DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n      \"server.bodySizeLimit\",\n    ),\n    trustProxy: config?.trustProxy === true,\n    headersTimeout,\n    requestTimeout,\n    keepAliveTimeout: parseFarmServerDuration(\n      config?.keepAliveTimeout ?? DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT,\n      \"server.keepAliveTimeout\",\n    ),\n    gracefulShutdownTimeout: parseFarmServerDuration(\n      config?.gracefulShutdownTimeout ?? DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,\n      \"server.gracefulShutdownTimeout\",\n    ),\n    health: resolveFarmServerHealthConfig(config?.health),\n  });\n}\n\nexport function parseFarmServerDuration(\n  value: FarmServerDuration,\n  optionName = \"duration\",\n): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    if (value > MAX_FARM_SERVER_TIMEOUT) {\n      throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be milliseconds or a duration such as \"30s\" or \"2m\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2];\n  const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n  const milliseconds = Math.floor(amount * multiplier);\n  if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n  if (milliseconds > MAX_FARM_SERVER_TIMEOUT) {\n    throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n  }\n  return milliseconds;\n}\n\nfunction resolveFarmServerHealthConfig(\n  config: false | FarmServerHealthConfig | ResolvedFarmServerHealthConfig | undefined,\n): ResolvedFarmServerHealthConfig {\n  if (config === false || (config && \"enabled\" in config && config.enabled === false)) {\n    return Object.freeze({\n      enabled: false,\n      livenessPath: \"/_farm/health/live\",\n      readinessPath: \"/_farm/health/ready\",\n    });\n  }\n\n  const livenessPath = normalizeHealthPath(\n    config?.livenessPath ?? \"/_farm/health/live\",\n    \"server.health.livenessPath\",\n  );\n  const readinessPath = normalizeHealthPath(\n    config?.readinessPath ?? \"/_farm/health/ready\",\n    \"server.health.readinessPath\",\n  );\n  if (livenessPath === readinessPath) {\n    throw new TypeError(\"server.health livenessPath and readinessPath must be different\");\n  }\n\n  return Object.freeze({ enabled: true, livenessPath, readinessPath });\n}\n\nfunction normalizeHealthPath(value: string, optionName: string): string {\n  const path = value.trim();\n  if (!path.startsWith(\"/\") || path.includes(\"?\") || path.includes(\"#\") || path.includes(\"*\")) {\n    throw new TypeError(`${optionName} must be an absolute pathname without a query or wildcard`);\n  }\n  const normalized = path.length > 1 ? path.replace(/\\/+$/, \"\") || \"/\" : path;\n  assertBrowserStableRoutePath(normalized);\n  return normalized;\n}\n\nexport function parseBodySizeLimit(value: number | string, optionName = \"bodySizeLimit\"): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)?$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be bytes or a size string such as \"500kb\" or \"10mb\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2] ?? \"b\";\n  const multiplier: Record<string, number> = {\n    b: 1,\n    kb: 1_000,\n    mb: 1_000_000,\n    gb: 1_000_000_000,\n    kib: 1_024,\n    mib: 1_048_576,\n    gib: 1_073_741_824,\n  };\n  const bytes = Math.floor(amount * multiplier[unit]);\n\n  if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n\n  return bytes;\n}\n\nexport async function bufferFarmRequestBody(request: Request, limit: number): Promise<Request> {\n  if (request.method === \"GET\" || request.method === \"HEAD\" || request.body === null) {\n    return request;\n  }\n\n  const bytes = await readFarmRequestBody(request, limit);\n  const body = new Uint8Array(bytes.byteLength);\n  body.set(bytes);\n  return new Request(request, {\n    // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.\n    body: body.buffer,\n  });\n}\n\nexport async function readFarmRequestBody(request: Request, limit: number): Promise<Uint8Array> {\n  try {\n    validateContentLength(request.headers.get(\"content-length\"), limit);\n  } catch (error) {\n    // A cloned Request is a tee branch: its cancellation may wait for the\n    // untouched branch. Rejection must not wait for producer-owned cleanup.\n    void request.body?.cancel(error).catch(() => {});\n    throw error;\n  }\n  throwIfAborted(request.signal);\n  if (!request.body) return new Uint8Array();\n\n  const reader = request.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  const cancelBodyRead = () => {\n    void reader.cancel(request.signal.reason).catch(() => {});\n  };\n  request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n  try {\n    while (true) {\n      throwIfAborted(request.signal);\n      const { done, value } = await reader.read();\n      // Cancellation resolves a pending read as EOF, not necessarily an error.\n      throwIfAborted(request.signal);\n      if (done) break;\n      if (!value) continue;\n\n      total += value.byteLength;\n      if (total > limit) {\n        const error = new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } catch (error) {\n    if (request.signal.aborted) throwIfAborted(request.signal);\n    throw error;\n  } finally {\n    request.signal.removeEventListener(\"abort\", cancelBodyRead);\n    reader.releaseLock();\n  }\n\n  const body = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    body.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return body;\n}\n\nexport async function readNodeRequestBody(\n  request: {\n    headers: Record<string, string | string[] | undefined>;\n    on(event: \"data\", listener: (chunk: unknown) => void): unknown;\n    on(event: \"end\", listener: () => void): unknown;\n    on(event: \"error\", listener: (error: Error) => void): unknown;\n    removeListener?(event: string, listener: (...args: any[]) => void): unknown;\n    resume?(): unknown;\n  },\n  limit: number,\n): Promise<Buffer> {\n  const rawContentLength = request.headers[\"content-length\"];\n  const contentLength = Array.isArray(rawContentLength) ? rawContentLength[0] : rawContentLength;\n  try {\n    validateContentLength(contentLength, limit);\n  } catch (error) {\n    request.resume?.();\n    throw error;\n  }\n\n  return await new Promise<Buffer>((resolve, reject) => {\n    const chunks: Buffer[] = [];\n    let total = 0;\n    let settled = false;\n\n    const cleanup = () => {\n      request.removeListener?.(\"data\", onData);\n      request.removeListener?.(\"end\", onEnd);\n      request.removeListener?.(\"error\", onError);\n    };\n    const rejectOnce = (error: Error) => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      request.resume?.();\n      reject(error);\n    };\n    const onData = (chunk: unknown) => {\n      const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as any);\n      total += bytes.byteLength;\n      if (total > limit) {\n        rejectOnce(new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\"));\n        return;\n      }\n      chunks.push(bytes);\n    };\n    const onEnd = () => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      resolve(Buffer.concat(chunks, total));\n    };\n    const onError = (error: Error) => rejectOnce(error);\n\n    request.on(\"data\", onData);\n    request.on(\"end\", onEnd);\n    request.on(\"error\", onError);\n  });\n}\n\nexport function createFarmRequestBodyErrorResponse(error: unknown): Response | null {\n  if (!(error instanceof FarmRequestBodyError)) return null;\n\n  return new Response(error.status === 413 ? \"Payload Too Large\" : \"Bad Request\", {\n    status: error.status,\n    headers: {\n      \"cache-control\": \"no-store\",\n      \"content-type\": \"text/plain; charset=utf-8\",\n      \"x-content-type-options\": \"nosniff\",\n    },\n  });\n}\n\nfunction validateContentLength(value: string | null | undefined, limit: number): void {\n  const contentLength = value?.trim();\n  if (!contentLength) return;\n  if (!/^\\d+$/.test(contentLength)) {\n    throw new FarmRequestBodyError(\"INVALID_CONTENT_LENGTH\", 400, \"Invalid content-length header\");\n  }\n  if (Number(contentLength) > limit) {\n    throw new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (!signal.aborted) return;\n  if (signal.reason !== undefined) throw signal.reason;\n  throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface FarmDocsPublicFontAsset {\n  family: \"Geist Sans\" | \"Geist Mono\";\n  url: string;\n}\n\nexport interface FarmDocsFontAsset extends FarmDocsPublicFontAsset {\n  sourcePath: string;\n}\n\nconst FARM_DOCS_FONT_SOURCES = [\n  {\n    family: \"Geist Sans\",\n    packagePath: \"geist/dist/fonts/geist-sans/Geist-Variable.woff2\",\n  },\n  {\n    family: \"Geist Mono\",\n    packagePath: \"geist/dist/fonts/geist-mono/GeistMono-Variable.woff2\",\n  },\n] as const;\n\nexport function resolveFarmDocsFontAssets(root: string): FarmDocsFontAsset[] {\n  return FARM_DOCS_FONT_SOURCES.flatMap(({ family, packagePath }) => {\n    const sourcePath = path.join(root, \"node_modules\", packagePath);\n    if (!existsSync(sourcePath)) return [];\n\n    const source = readFileSync(sourcePath);\n    const fingerprint = createHash(\"sha256\").update(source).digest(\"hex\").slice(0, 12);\n    const extension = path.extname(packagePath);\n    const baseName = path.basename(packagePath, extension);\n\n    return [\n      {\n        family,\n        sourcePath,\n        url: `/assets/fonts/${baseName}-h${fingerprint}${extension}`,\n      },\n    ];\n  });\n}\n\nexport function toFarmDocsPublicFontAssets(\n  assets: readonly FarmDocsFontAsset[],\n): FarmDocsPublicFontAsset[] {\n  return assets.map(({ family, url }) => ({ family, url }));\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const FARM_DOCS_LAST_MODIFIED_MANIFEST = \".farm-docs-last-modified.json\";\n\nexport interface FarmDocsLastModifiedManifest {\n  version: 1;\n  pages: Record<string, string>;\n}\n\nexport interface CreateFarmDocsLastModifiedManifestOptions {\n  fallback?: \"mtime\" | \"now\";\n  now?: Date;\n}\n\nconst COMMIT_MARKER = \"__FARM_DOCS_COMMIT__\";\nconst DOCS_FILE_EXTENSIONS = new Set([\".md\", \".mdx\"]);\nconst manifestCache = new Map<\n  string,\n  {\n    signature: string;\n    manifest: FarmDocsLastModifiedManifest;\n  }\n>();\n\nfunction normalizeRelativePath(value: string): string {\n  return value.replace(/\\\\/g, \"/\").replace(/^\\.\\/+/, \"\");\n}\n\nfunction resolveExistingPath(filePath: string): string {\n  try {\n    return realpathSync(filePath);\n  } catch {\n    return path.resolve(filePath);\n  }\n}\n\nfunction isDocsSourceFile(filePath: string): boolean {\n  return DOCS_FILE_EXTENSIONS.has(path.extname(filePath).toLowerCase());\n}\n\nfunction discoverDocsSourceFiles(contentDir: string): string[] {\n  const files: string[] = [];\n\n  const visit = (dir: string) => {\n    for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>\n      a.name.localeCompare(b.name),\n    )) {\n      if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\n      const absolutePath = path.join(dir, entry.name);\n      if (entry.isDirectory()) {\n        visit(absolutePath);\n      } else if (entry.isFile() && isDocsSourceFile(absolutePath)) {\n        files.push(absolutePath);\n      }\n    }\n  };\n\n  if (existsSync(contentDir)) visit(contentDir);\n  return files;\n}\n\nfunction getGitLastModifiedDates(contentDir: string): Record<string, string> {\n  try {\n    const gitRoot = execFileSync(\"git\", [\"-C\", contentDir, \"rev-parse\", \"--show-toplevel\"], {\n      encoding: \"utf8\",\n      stdio: [\"ignore\", \"pipe\", \"ignore\"],\n    }).trim();\n    if (!gitRoot) return {};\n\n    const contentPathspec = normalizeRelativePath(path.relative(gitRoot, contentDir)) || \".\";\n    const contentPrefix = contentPathspec === \".\" ? \"\" : `${contentPathspec}/`;\n    const history = execFileSync(\n      \"git\",\n      [\n        \"-C\",\n        gitRoot,\n        \"-c\",\n        \"core.quotePath=false\",\n        \"log\",\n        `--format=${COMMIT_MARKER}%cI`,\n        \"--name-only\",\n        \"--\",\n        contentPathspec,\n      ],\n      {\n        encoding: \"utf8\",\n        stdio: [\"ignore\", \"pipe\", \"ignore\"],\n        maxBuffer: 32 * 1024 * 1024,\n      },\n    );\n\n    const pages: Record<string, string> = {};\n    let commitDate: string | undefined;\n\n    for (const rawLine of history.split(/\\r?\\n/)) {\n      const line = normalizeRelativePath(rawLine.trim());\n      if (!line) continue;\n\n      if (line.startsWith(COMMIT_MARKER)) {\n        commitDate = line.slice(COMMIT_MARKER.length);\n        continue;\n      }\n      if (!commitDate || (contentPrefix && !line.startsWith(contentPrefix))) continue;\n\n      const relativePath = contentPrefix ? line.slice(contentPrefix.length) : line;\n      if (isDocsSourceFile(relativePath) && !pages[relativePath]) {\n        pages[relativePath] = commitDate;\n      }\n    }\n\n    return pages;\n  } catch {\n    return {};\n  }\n}\n\nfunction readManifest(contentDir: string): FarmDocsLastModifiedManifest | null {\n  const manifestPath = path.join(contentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST);\n  if (!existsSync(manifestPath)) return null;\n\n  try {\n    const parsed = JSON.parse(\n      readFileSync(manifestPath, \"utf8\"),\n    ) as Partial<FarmDocsLastModifiedManifest>;\n    if (parsed.version !== 1 || !parsed.pages || typeof parsed.pages !== \"object\") return null;\n\n    const pages = Object.fromEntries(\n      Object.entries(parsed.pages).filter(\n        (entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1].length > 0,\n      ),\n    );\n    return { version: 1, pages };\n  } catch {\n    return null;\n  }\n}\n\nexport function createFarmDocsLastModifiedManifest(\n  contentDir: string,\n  options: CreateFarmDocsLastModifiedManifestOptions = {},\n): FarmDocsLastModifiedManifest {\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const gitDates = getGitLastModifiedDates(resolvedContentDir);\n  const fallbackDate = (options.now ?? new Date()).toISOString();\n  const pages: Record<string, string> = {};\n\n  for (const sourcePath of discoverDocsSourceFiles(resolvedContentDir)) {\n    const relativePath = normalizeRelativePath(path.relative(resolvedContentDir, sourcePath));\n    pages[relativePath] =\n      gitDates[relativePath] ||\n      (options.fallback === \"now\" ? fallbackDate : statSync(sourcePath).mtime.toISOString());\n  }\n\n  return { version: 1, pages };\n}\n\nfunction getLastModifiedManifest(contentDir: string): FarmDocsLastModifiedManifest {\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const manifestPath = path.join(resolvedContentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST);\n  const manifestStat = existsSync(manifestPath) ? statSync(manifestPath) : null;\n  const signature = manifestStat\n    ? `file:${manifestStat.mtimeMs}:${manifestStat.size}`\n    : \"generated\";\n  const cached = manifestCache.get(resolvedContentDir);\n  if (cached?.signature === signature) return cached.manifest;\n\n  const manifest =\n    readManifest(resolvedContentDir) ?? createFarmDocsLastModifiedManifest(resolvedContentDir);\n  manifestCache.set(resolvedContentDir, { signature, manifest });\n  return manifest;\n}\n\nexport function resolveFarmDocsPageLastModified(\n  contentDir: string,\n  sourcePath: string,\n  frontmatter: Record<string, string>,\n): string {\n  const configured =\n    frontmatter.lastModified ||\n    frontmatter.lastmod ||\n    frontmatter.lastUpdated ||\n    frontmatter.updatedAt;\n  if (configured) return configured;\n\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const resolvedSourcePath = resolveExistingPath(sourcePath);\n  const relativePath = normalizeRelativePath(path.relative(resolvedContentDir, resolvedSourcePath));\n  const isInsideContentDir =\n    relativePath !== \"..\" && !relativePath.startsWith(\"../\") && !path.isAbsolute(relativePath);\n\n  if (isInsideContentDir) {\n    const generated = getLastModifiedManifest(resolvedContentDir).pages[relativePath];\n    if (generated) return generated;\n  }\n\n  return statSync(resolvedSourcePath).mtime.toISOString();\n}\n","import { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\nexport function isFarmDocsSearchEnabled(docs: FarmDocsResolvedConfig | undefined): boolean {\n  if (!docs?.enabled) return false;\n\n  const search = docs.config.search;\n  if (search === false) return false;\n  return !(search && typeof search === \"object\" && search.enabled === false);\n}\n\nexport function resolveFarmDocsSearchClientModule(root: string): string | undefined {\n  try {\n    const requireFromApp = createRequire(path.join(path.resolve(root), \"package.json\"));\n    const themeEntry = requireFromApp.resolve(\"@farming-labs/theme\");\n    const commandSearchModule = path.join(path.dirname(themeEntry), \"docs-command-search.mjs\");\n    if (existsSync(commandSearchModule)) return commandSearchModule;\n  } catch {\n    // The public package entry remains a compatible fallback.\n  }\n\n  return undefined;\n}\n\nexport function generateFarmDocsSearchBootstrapRuntime(): string {\n  return `(()=>{if(window.__farmDocsSearchBootstrap)return;window.__farmDocsSearchBootstrap=true;const queue=(trigger,event)=>{if(window.__FARM_DOCS_SEARCH_BRIDGE_ACTIVE__)return;event.preventDefault();event.stopPropagation();event.stopImmediatePropagation();window.__FARM_DOCS_SEARCH_PENDING__=trigger;window.__FARM_MOUNT_DOCS_SEARCH__?.()};document.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"[data-search-full]\"):null;if(target)queue(\"button\",event)},true);document.addEventListener(\"keydown\",(event)=>{if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()===\"k\")queue(\"keyboard\",event)},true)})();`;\n}\n\nexport function generateFarmDocsSearchClientRuntime(enabled: boolean, moduleId?: string): string {\n  if (!enabled || !moduleId) {\n    return `\nfunction isFarmDocsSearchPage() {\n  return false;\n}\n\nasync function mountFarmDocsSearch() {\n  return false;\n}\n`;\n  }\n\n  return `\nlet farmDocsSearchRoot = null;\nlet farmDocsSearchContainer = null;\nlet farmDocsSearchModulePromise = null;\nlet farmDocsSearchPendingTrigger = window.__FARM_DOCS_SEARCH_PENDING__ === 'keyboard'\n  ? 'keyboard'\n  : window.__FARM_DOCS_SEARCH_PENDING__\n    ? 'button'\n    : null;\nlet farmDocsSearchReady = false;\n\nfunction isFarmDocsSearchPage() {\n  return document.querySelector('[data-farm-docs-search-root]') instanceof HTMLElement;\n}\n\nfunction replayFarmDocsSearchOpen() {\n  const pendingTrigger = farmDocsSearchPendingTrigger;\n  farmDocsSearchPendingTrigger = null;\n  window.__FARM_DOCS_SEARCH_PENDING__ = null;\n  if (!pendingTrigger) return;\n\n  queueMicrotask(() => {\n    if (pendingTrigger === 'keyboard') {\n      document.dispatchEvent(\n        new KeyboardEvent('keydown', {\n          key: 'k',\n          metaKey: true,\n          bubbles: true,\n          cancelable: true,\n        }),\n      );\n    } else {\n      const trigger = document.querySelector('[data-search-full]');\n      if (trigger instanceof HTMLElement) trigger.click();\n    }\n  });\n}\n\nfunction FarmDocsSearchBridge({ component, api }) {\n  React.useEffect(() => {\n    farmDocsSearchReady = true;\n    replayFarmDocsSearchOpen();\n    return () => {\n      farmDocsSearchReady = false;\n    };\n  }, []);\n\n  return React.createElement(component, { api });\n}\n\nfunction queueFarmDocsSearchOpen(trigger, event) {\n  if (farmDocsSearchReady) return;\n  event.preventDefault();\n  event.stopPropagation();\n  event.stopImmediatePropagation();\n  farmDocsSearchPendingTrigger = trigger;\n  window.__FARM_DOCS_SEARCH_PENDING__ = trigger;\n  void mountFarmDocsSearch();\n}\n\ndocument.addEventListener(\n  'click',\n  (event) => {\n    const target = event.target instanceof Element\n      ? event.target.closest('[data-search-full]')\n      : null;\n    if (target) queueFarmDocsSearchOpen('button', event);\n  },\n  true,\n);\n\ndocument.addEventListener(\n  'keydown',\n  (event) => {\n    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {\n      queueFarmDocsSearchOpen('keyboard', event);\n    }\n  },\n  true,\n);\n\nwindow.__FARM_DOCS_SEARCH_BRIDGE_ACTIVE__ = true;\n\nasync function mountFarmDocsSearch() {\n  const container = document.querySelector('[data-farm-docs-search-root]');\n  if (!(container instanceof HTMLElement)) return false;\n  if (farmDocsSearchContainer === container && farmDocsSearchRoot) return true;\n\n  try {\n    farmDocsSearchModulePromise ||= import(${JSON.stringify(moduleId)});\n    const { DocsCommandSearch } = await farmDocsSearchModulePromise;\n    if (!container.isConnected) return false;\n\n    if (farmDocsSearchRoot) {\n      farmDocsSearchReady = false;\n      try {\n        farmDocsSearchRoot.unmount();\n      } catch {}\n    }\n\n    farmDocsSearchContainer = container;\n    farmDocsSearchRoot = createRoot(container);\n    farmDocsSearchRoot.render(\n      React.createElement(FarmDocsSearchBridge, {\n        component: DocsCommandSearch,\n        api: container.dataset.api || '/api/docs',\n      }),\n    );\n    return true;\n  } catch (error) {\n    farmDocsSearchModulePromise = null;\n    console.error('[Farm.js] Could not load docs search:', error);\n    return false;\n  }\n}\n\nwindow.__FARM_MOUNT_DOCS_SEARCH__ = mountFarmDocsSearch;\n`;\n}\n","import { createHash } from \"node:crypto\";\nimport type { LoadedFarmDocsPage } from \"./handler\";\nimport type {\n  FarmDocsResolvedConfig,\n  FarmDocsSocialImageConfig,\n  FarmDocsSocialImageFonts,\n} from \"./types\";\n\nexport const FARM_DOCS_SOCIAL_IMAGE_WIDTH = 1200;\nexport const FARM_DOCS_SOCIAL_IMAGE_HEIGHT = 630;\n\nexport interface FarmDocsSocialImageDescriptor {\n  title: string;\n  description: string;\n  section: string;\n  siteName: string;\n  brand: string;\n  pageHref: string;\n  pageUrl: string;\n  imagePath: string;\n  imageUrl: string;\n  imageAlt: string;\n  illustration: FarmDocsSocialImageIllustration;\n  fonts?: FarmDocsSocialImageFonts;\n  hash: string;\n}\n\nexport type FarmDocsSocialImageIllustration =\n  | \"auth\"\n  | \"cache\"\n  | \"cli\"\n  | \"integrations\"\n  | \"project\"\n  | \"routing\"\n  | \"runtime\";\n\nconst FARM_DOCS_SOCIAL_IMAGE_VERSION = 3;\n\nfunction normalizeEntry(entry: string): string {\n  if (!entry || entry === \"/\") return \"\";\n  return `/${entry.replace(/^\\/+|\\/+$/g, \"\")}`;\n}\n\nfunction encodeSlugPath(slug: string): string {\n  return slug\n    .split(\"/\")\n    .filter(Boolean)\n    .map((segment) => encodeURIComponent(segment))\n    .join(\"/\");\n}\n\nfunction getSocialImageConfig(docs: FarmDocsResolvedConfig): FarmDocsSocialImageConfig | undefined {\n  return typeof docs.config.socialImage === \"object\" && docs.config.socialImage\n    ? docs.config.socialImage\n    : undefined;\n}\n\nfunction getNavTitle(docs: FarmDocsResolvedConfig): string {\n  if (typeof docs.config.nav !== \"object\" || !docs.config.nav || !(\"title\" in docs.config.nav)) {\n    return \"Farm.js\";\n  }\n  return String((docs.config.nav as { title?: unknown }).title || \"Farm.js\");\n}\n\nfunction isFalse(value: string | undefined): boolean {\n  return value ? /^(false|no|none|off|disabled)$/i.test(value.trim()) : false;\n}\n\nfunction isExternalOrRootPath(value: string): boolean {\n  return /^(https?:)?\\/\\//i.test(value) || value.startsWith(\"/\");\n}\n\nexport function isFarmDocsSocialImageEnabled(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n): boolean {\n  if (docs.config.socialImage === false || getSocialImageConfig(docs)?.enabled === false) {\n    return false;\n  }\n  return !isFalse(page.frontmatter.socialImage);\n}\n\nexport function getFarmDocsCustomSocialImage(page: LoadedFarmDocsPage): string | undefined {\n  const value =\n    page.frontmatter.socialImage || page.frontmatter.openGraphImage || page.frontmatter.ogImage;\n  return value && !isFalse(value) && isExternalOrRootPath(value) ? value : undefined;\n}\n\nfunction resolveIllustration(page: LoadedFarmDocsPage): FarmDocsSocialImageIllustration {\n  const explicit = page.frontmatter.socialIllustration?.toLowerCase();\n  if (\n    explicit === \"auth\" ||\n    explicit === \"cache\" ||\n    explicit === \"cli\" ||\n    explicit === \"integrations\" ||\n    explicit === \"project\" ||\n    explicit === \"routing\" ||\n    explicit === \"runtime\"\n  ) {\n    return explicit;\n  }\n\n  const source = `${page.slug} ${page.title} ${page.section || \"\"}`.toLowerCase();\n  if (/auth|session|security|csrf/.test(source)) return \"auth\";\n  if (/cache|ppr|render|static|revalid|stream/.test(source)) return \"cache\";\n  if (/integration|stripe|prisma|better.auth|email|job|workflow/.test(source)) {\n    return \"integrations\";\n  }\n  if (/cli|test|deploy|preview|upgrade|migration|install/.test(source)) return \"cli\";\n  if (/project|structure|config|environment|markdown|docs.engine/.test(source)) {\n    return \"project\";\n  }\n  if (/rout|endpoint|middleware|navigation|server.function|server.action|api/.test(source)) {\n    return \"routing\";\n  }\n  return \"runtime\";\n}\n\nfunction createHashValue(value: unknown): string {\n  return createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\").slice(0, 16);\n}\n\nfunction resolveBaseUrl(requestUrl: URL, config: FarmDocsSocialImageConfig | undefined): URL {\n  return config?.baseUrl ? new URL(config.baseUrl) : new URL(requestUrl.origin);\n}\n\nexport function createFarmDocsSocialImageDescriptor(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n  requestUrl: URL,\n): FarmDocsSocialImageDescriptor {\n  const config = getSocialImageConfig(docs);\n  const siteName = config?.siteName || getNavTitle(docs);\n  const brand = config?.brand || siteName;\n  const title = page.frontmatter.socialTitle || page.title;\n  const description =\n    page.frontmatter.socialDescription ||\n    page.description ||\n    docs.config.metadata?.description ||\n    `Documentation for ${siteName}`;\n  const section = page.frontmatter.section || page.section || \"Documentation\";\n  const illustration = resolveIllustration(page);\n  const entry = normalizeEntry(docs.entry);\n  const slugPath = encodeSlugPath(page.slug) || \"index\";\n  const imagePath = `${entry}/_social/${slugPath}/opengraph-image.svg`;\n  const baseUrl = resolveBaseUrl(requestUrl, config);\n  const pageUrl = new URL(page.href, baseUrl).href;\n  const imageAlt = `${title} — ${siteName} documentation`;\n  const hash = createHashValue({\n    version: FARM_DOCS_SOCIAL_IMAGE_VERSION,\n    title,\n    description,\n    section,\n    siteName,\n    brand,\n    pageHref: page.href,\n    illustration,\n    fonts: config?.fonts,\n  });\n\n  return {\n    title,\n    description,\n    section,\n    siteName,\n    brand,\n    pageHref: page.href,\n    pageUrl,\n    imagePath,\n    imageUrl: new URL(`${imagePath}?v=${hash}`, baseUrl).href,\n    imageAlt,\n    illustration,\n    fonts: config?.fonts,\n    hash,\n  };\n}\n\nexport function getFarmDocsSocialImageSlug(\n  docs: FarmDocsResolvedConfig,\n  requestUrl: URL,\n): string | null {\n  const entry = normalizeEntry(docs.entry);\n  const prefix = `${entry}/_social/`;\n  const suffix = \"/opengraph-image.svg\";\n  if (!requestUrl.pathname.startsWith(prefix) || !requestUrl.pathname.endsWith(suffix)) {\n    return null;\n  }\n\n  const rawSlug = requestUrl.pathname.slice(prefix.length, -suffix.length);\n  if (!rawSlug) return null;\n  try {\n    const slug = rawSlug\n      .split(\"/\")\n      .map((segment) => decodeURIComponent(segment))\n      .join(\"/\");\n    if (slug.split(\"/\").some((segment) => !segment || segment === \"..\" || segment === \".\")) {\n      return null;\n    }\n    return slug === \"index\" ? \"\" : slug;\n  } catch {\n    return null;\n  }\n}\n\nfunction escapeXml(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&apos;\");\n}\n\nfunction truncate(value: string, length: number): string {\n  if (value.length <= length) return value;\n  return `${value.slice(0, Math.max(0, length - 1)).trimEnd()}…`;\n}\n\nfunction wrapText(value: string, maxCharacters: number, maxLines: number): string[] {\n  const words = value.trim().split(/\\s+/).filter(Boolean);\n  const lines: string[] = [];\n  let current = \"\";\n  let consumedWords = 0;\n\n  for (const word of words) {\n    const candidate = current ? `${current} ${word}` : word;\n    if (candidate.length <= maxCharacters || !current) {\n      current = candidate;\n      consumedWords += 1;\n      continue;\n    }\n    lines.push(current);\n    if (lines.length === maxLines) break;\n    current = word;\n    consumedWords += 1;\n  }\n\n  if (current && lines.length < maxLines) lines.push(current);\n  if (consumedWords < words.length && lines.length) {\n    lines[lines.length - 1] = truncate(`${lines[lines.length - 1]}…`, maxCharacters);\n  }\n  return lines;\n}\n\nfunction renderTextLines(\n  lines: string[],\n  x: number,\n  y: number,\n  lineHeight: number,\n  attributes: string,\n): string {\n  return lines\n    .map(\n      (line, index) =>\n        `<text x=\"${x}\" y=\"${y + index * lineHeight}\" ${attributes}>${escapeXml(line)}</text>`,\n    )\n    .join(\"\");\n}\n\nfunction renderEmbeddedFont(name: string, source: string | undefined, weight: string): string {\n  if (!source) return \"\";\n  return `@font-face{font-family:\"${name}\";src:url(\"${escapeXml(source)}\") format(\"woff2\");font-style:normal;font-weight:${weight};font-display:block;}`;\n}\n\nfunction renderArrow(x1: number, y: number, x2: number, color = \"#8b8b8b\"): string {\n  return `<path d=\"M${x1} ${y}H${x2 - 9}\" fill=\"none\" stroke=\"${color}\"/><path d=\"m${x2 - 9} ${y - 5} 9 5-9 5\" fill=\"none\" stroke=\"${color}\"/>`;\n}\n\nfunction renderPanelHeader(label: string, status: string): string {\n  return `<text x=\"819\" y=\"171\" class=\"label\">${escapeXml(label)}</text><text x=\"1134\" y=\"171\" class=\"label bright\" text-anchor=\"end\">${escapeXml(status)}</text>`;\n}\n\nfunction renderRoutingIllustration(): string {\n  return `${renderPanelHeader(\"ROUTE BLUEPRINT\", \"TYPED\")}\n    <rect x=\"819\" y=\"296\" width=\"92\" height=\"54\" fill=\"#a3a3a3\"/>\n    <text x=\"832\" y=\"327\" class=\"diagram-title ink\">src/app</text>\n    <path d=\"M911 323h41M952 232v181M952 232h44M952 323h44M952 413h44\" fill=\"none\" stroke=\"#696969\"/>\n    <rect x=\"996\" y=\"205\" width=\"138\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#414141\"/>\n    <text x=\"1010\" y=\"228\" class=\"diagram-title\">/</text><text x=\"1010\" y=\"246\" class=\"micro\">STATIC</text>\n    <rect x=\"996\" y=\"296\" width=\"138\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#414141\"/>\n    <text x=\"1010\" y=\"319\" class=\"diagram-title\">/blog/:slug</text><text x=\"1010\" y=\"337\" class=\"micro\">DYNAMIC</text>\n    <rect x=\"996\" y=\"386\" width=\"138\" height=\"55\" fill=\"#f0f0f0\"/>\n    <text x=\"1010\" y=\"410\" class=\"diagram-title ink\">/docs/:path*</text><text x=\"1010\" y=\"428\" class=\"micro ink-muted\">CATCH-ALL</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">FILE ROUTES</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">TYPES INCLUDED</text>`;\n}\n\nfunction renderAuthIllustration(): string {\n  return `${renderPanelHeader(\"REQUEST GUARD\", \"SERVER VERIFIED\")}\n    <rect x=\"819\" y=\"269\" width=\"86\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#454545\"/>\n    <text x=\"837\" y=\"292\" class=\"micro bright\">REQUEST</text><text x=\"837\" y=\"310\" class=\"diagram-title\">GET /app</text>\n    ${renderArrow(905, 296, 943)}\n    <rect x=\"943\" y=\"224\" width=\"104\" height=\"118\" fill=\"#f0f0f0\"/>\n    <path d=\"M974 271v-12a21 21 0 0 1 42 0v12M968 271h54v45h-54z\" fill=\"#050505\"/>\n    <circle cx=\"995\" cy=\"292\" r=\"4\" fill=\"#f0f0f0\"/><path d=\"M995 296v8\" stroke=\"#f0f0f0\" stroke-width=\"3\"/>\n    <text x=\"995\" y=\"332\" class=\"micro ink\" text-anchor=\"middle\">auth()</text>\n    ${renderArrow(1047, 296, 1071)}\n    <rect x=\"1071\" y=\"269\" width=\"63\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#454545\"/>\n    <text x=\"1082\" y=\"292\" class=\"micro bright\">ALLOW</text><text x=\"1082\" y=\"310\" class=\"micro\">/app</text>\n    <rect x=\"819\" y=\"372\" width=\"315\" height=\"38\" fill=\"#090909\" stroke=\"#3d3d3d\"/>\n    <rect x=\"832\" y=\"385\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/>\n    <text x=\"856\" y=\"395\" class=\"code\">session.user / verified</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">SESSION TYPED</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">CSRF PROTECTED</text>`;\n}\n\nfunction renderCacheIllustration(): string {\n  return `${renderPanelHeader(\"PAGE / PRODUCT\", \"CACHE + PPR\")}\n    <rect x=\"819\" y=\"204\" width=\"315\" height=\"54\" fill=\"#f0f0f0\"/>\n    <text x=\"836\" y=\"235\" class=\"diagram-title ink\">STATIC SHELL</text><text x=\"1116\" y=\"235\" class=\"micro ink-muted\" text-anchor=\"end\">BUILD</text>\n    <rect x=\"819\" y=\"271\" width=\"198\" height=\"76\" fill=\"#a3a3a3\"/>\n    <text x=\"836\" y=\"301\" class=\"diagram-title ink\">CACHED DATA</text><text x=\"836\" y=\"326\" class=\"micro ink-muted\">tag: products</text>\n    <rect x=\"1029\" y=\"271\" width=\"105\" height=\"76\" fill=\"#0a0a0a\" stroke=\"#555\"/>\n    <text x=\"1045\" y=\"301\" class=\"diagram-title\">LIVE</text><text x=\"1045\" y=\"326\" class=\"micro\">stream</text>\n    <path d=\"M1081 347v43m-8-9 8 9 8-9\" fill=\"none\" stroke=\"#d4d4d4\"/>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">STATIC FIRST</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">DYNAMIC WHERE NEEDED</text>`;\n}\n\nfunction renderIntegrationsIllustration(): string {\n  return `${renderPanelHeader(\"INTEGRATION GRAPH\", \"ONE PRODUCT\")}\n    <path d=\"M976 309H879V247M976 309H879v87M1030 309h93V247M1030 309h93v87\" fill=\"none\" stroke=\"#4a4a4a\"/>\n    <rect x=\"819\" y=\"214\" width=\"120\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"839\" y=\"247\" class=\"diagram-title\">BETTER AUTH</text>\n    <rect x=\"819\" y=\"368\" width=\"120\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"851\" y=\"401\" class=\"diagram-title\">PRISMA</text>\n    <rect x=\"1061\" y=\"214\" width=\"73\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"1077\" y=\"247\" class=\"diagram-title\">STRIPE</text>\n    <rect x=\"1061\" y=\"368\" width=\"73\" height=\"57\" fill=\"#a3a3a3\"/><text x=\"1075\" y=\"401\" class=\"diagram-title ink\">VERCEL</text>\n    <rect x=\"976\" y=\"277\" width=\"94\" height=\"64\" fill=\"#f0f0f0\"/>\n    <text x=\"994\" y=\"304\" class=\"diagram-title ink\">FARM.JS</text><text x=\"994\" y=\"324\" class=\"micro ink-muted\">CORE</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">BRING YOUR STACK</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">CONNECTED ONCE</text>`;\n}\n\nfunction renderCliIllustration(): string {\n  return `${renderPanelHeader(\"TERMINAL\", \"PRODUCTION OUTPUT\")}\n    <rect x=\"819\" y=\"203\" width=\"315\" height=\"213\" fill=\"#050505\" stroke=\"#555\"/>\n    <line x1=\"819\" y1=\"236\" x2=\"1134\" y2=\"236\" stroke=\"#555\"/>\n    <circle cx=\"837\" cy=\"220\" r=\"4\" fill=\"#5d5d5d\"/><circle cx=\"850\" cy=\"220\" r=\"4\" fill=\"#7a7a7a\"/><circle cx=\"863\" cy=\"220\" r=\"4\" fill=\"#a3a3a3\"/>\n    <text x=\"837\" y=\"273\" class=\"code bright\"><tspan fill=\"#7a7a7a\">$</tspan> farm build</text>\n    <rect x=\"837\" y=\"293\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/><path d=\"m839 298 3 3 6-7\" fill=\"none\" stroke=\"#050505\" stroke-width=\"1.5\"/>\n    <text x=\"861\" y=\"303\" class=\"code\">64 routes discovered</text>\n    <rect x=\"837\" y=\"320\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/><path d=\"m839 325 3 3 6-7\" fill=\"none\" stroke=\"#050505\" stroke-width=\"1.5\"/>\n    <text x=\"861\" y=\"330\" class=\"code\">client + server bundles</text>\n    <rect x=\"837\" y=\"355\" width=\"126\" height=\"30\" fill=\"#f0f0f0\"/><text x=\"853\" y=\"374\" class=\"micro ink\">BUILD COMPLETE</text>\n    <text x=\"1115\" y=\"374\" class=\"micro\" text-anchor=\"end\">/dist</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">REAL COMMANDS</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">842MS</text>`;\n}\n\nfunction renderProjectIllustration(): string {\n  return `${renderPanelHeader(\"PROJECT MAP\", \"CONVENTION TYPED\")}\n    <rect x=\"819\" y=\"202\" width=\"315\" height=\"216\" fill=\"#050505\" stroke=\"#555\"/>\n    <text x=\"837\" y=\"227\" class=\"diagram-title bright\">my-app/</text>\n    <path d=\"M847 243v143M847 259h23M847 293h23M847 327h23M847 361h23\" fill=\"none\" stroke=\"#666\"/>\n    <rect x=\"870\" y=\"243\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"264\" class=\"code\">src/app</text><text x=\"1098\" y=\"264\" class=\"micro\" text-anchor=\"end\">ROUTES</text>\n    <rect x=\"870\" y=\"277\" width=\"246\" height=\"33\" fill=\"#f0f0f0\"/><text x=\"886\" y=\"298\" class=\"code ink\">src/app/page.tsx</text>\n    <rect x=\"870\" y=\"311\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"332\" class=\"code\">src/app/api/users/route.ts</text><text x=\"1098\" y=\"332\" class=\"micro\" text-anchor=\"end\">API</text>\n    <rect x=\"870\" y=\"345\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"366\" class=\"code\">farm.config.ts</text><text x=\"1098\" y=\"366\" class=\"micro\" text-anchor=\"end\">CONFIG</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">FILES BECOME FEATURES</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">ONE CONFIG</text>`;\n}\n\nfunction renderRuntimeIllustration(): string {\n  return `${renderPanelHeader(\"PRODUCT ARCHITECTURE\", \"FULL STACK\")}\n    <rect x=\"819\" y=\"211\" width=\"315\" height=\"55\" fill=\"#f0f0f0\"/>\n    <text x=\"836\" y=\"244\" class=\"diagram-title ink\">PRODUCT SURFACE</text><text x=\"1116\" y=\"244\" class=\"micro ink-muted\" text-anchor=\"end\">UI + ROUTES</text>\n    <path d=\"M976 266v20m0 61v20\" stroke=\"#727272\"/>\n    <rect x=\"855\" y=\"286\" width=\"242\" height=\"61\" fill=\"#a3a3a3\"/>\n    <text x=\"874\" y=\"314\" class=\"diagram-title ink\">APPLICATION CORE</text><text x=\"874\" y=\"334\" class=\"micro ink-muted\">APIS · MIDDLEWARE</text>\n    <rect x=\"819\" y=\"367\" width=\"315\" height=\"55\" fill=\"#4c4c4c\"/>\n    <text x=\"836\" y=\"400\" class=\"diagram-title bright\">CONNECTED STACK</text><text x=\"1116\" y=\"400\" class=\"micro\" text-anchor=\"end\">DATA · AUTH · DEPLOY</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">ONE FRAMEWORK</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">ONE DEPLOYMENT MODEL</text>`;\n}\n\nfunction renderIllustration(type: FarmDocsSocialImageIllustration): string {\n  switch (type) {\n    case \"auth\":\n      return renderAuthIllustration();\n    case \"cache\":\n      return renderCacheIllustration();\n    case \"cli\":\n      return renderCliIllustration();\n    case \"integrations\":\n      return renderIntegrationsIllustration();\n    case \"project\":\n      return renderProjectIllustration();\n    case \"routing\":\n      return renderRoutingIllustration();\n    default:\n      return renderRuntimeIllustration();\n  }\n}\n\nexport function renderFarmDocsSocialImageSvg(descriptor: FarmDocsSocialImageDescriptor): string {\n  const titleLines = wrapText(descriptor.title, 22, 2);\n  const longestTitleLine = Math.max(...titleLines.map((line) => line.length));\n  const titleSize = titleLines.length === 1 ? (longestTitleLine > 17 ? 62 : 74) : 56;\n  const titleLineHeight = Math.round(titleSize * 0.98);\n  const titleY = titleLines.length === 1 ? 294 : 266;\n  const descriptionY = titleY + (titleLines.length - 1) * titleLineHeight + 59;\n  const descriptionLines = wrapText(descriptor.description, 68, 2);\n  const routeY = Math.max(418, descriptionY + descriptionLines.length * 29 + 24);\n  const section = truncate(descriptor.section.toUpperCase(), 27);\n  const route = truncate(descriptor.pageHref, 42);\n  const footerUrl = truncate(descriptor.pageUrl.replace(/^https?:\\/\\//, \"\"), 70);\n  const brand = truncate(descriptor.brand.toUpperCase(), 25);\n  const titleId = `farm-docs-og-${descriptor.hash}`;\n\n  return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"${FARM_DOCS_SOCIAL_IMAGE_WIDTH}\" height=\"${FARM_DOCS_SOCIAL_IMAGE_HEIGHT}\" viewBox=\"0 0 ${FARM_DOCS_SOCIAL_IMAGE_WIDTH} ${FARM_DOCS_SOCIAL_IMAGE_HEIGHT}\" role=\"img\" aria-labelledby=\"${titleId}-title ${titleId}-description\">\n  <title id=\"${titleId}-title\">${escapeXml(descriptor.imageAlt)}</title>\n  <desc id=\"${titleId}-description\">${escapeXml(descriptor.description)}</desc>\n  <metadata>${escapeXml(JSON.stringify({ generator: \"Farm.js docs\", page: descriptor.pageUrl, illustration: descriptor.illustration }))}</metadata>\n  <style type=\"text/css\">\n    ${renderEmbeddedFont(\"Farm Sans\", descriptor.fonts?.sans, \"100 900\")}\n    ${renderEmbeddedFont(\"Farm Mono\", descriptor.fonts?.mono, \"100 900\")}\n    ${renderEmbeddedFont(\"Farm Pixel\", descriptor.fonts?.display, \"400 700\")}\n    .sans{font-family:\"Farm Sans\",\"Arial\",sans-serif}.mono,.label,.code,.diagram-title,.micro{font-family:\"Farm Mono\",\"Menlo\",\"DejaVu Sans Mono\",monospace}.pixel{font-family:\"Farm Pixel\",\"Farm Mono\",monospace}.label{fill:#8b8b8b;font-size:10px;font-weight:600;letter-spacing:1.2px}.code{fill:#8b8b8b;font-size:11px}.diagram-title{fill:#e7e7e7;font-size:11px;font-weight:650}.micro{fill:#777;font-size:8px;letter-spacing:.45px}.bright{fill:#f5f5f4}.ink{fill:#050505}.ink-muted{fill:#4c4c4c}\n  </style>\n  <defs>\n    <pattern id=\"canvas-grid\" width=\"40\" height=\"40\" patternUnits=\"userSpaceOnUse\"><path d=\"M40 0H0V40\" fill=\"none\" stroke=\"#151515\"/></pattern>\n    <pattern id=\"diagonal\" width=\"12\" height=\"12\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\"><line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"12\" stroke=\"#171717\" stroke-width=\"2\"/></pattern>\n    <clipPath id=\"frame-clip\"><rect x=\"28\" y=\"28\" width=\"1144\" height=\"574\"/></clipPath>\n  </defs>\n  <rect width=\"1200\" height=\"630\" fill=\"#050505\"/>\n  <rect width=\"1200\" height=\"630\" fill=\"url(#canvas-grid)\"/>\n  <g clip-path=\"url(#frame-clip)\">\n    <rect x=\"28\" y=\"28\" width=\"1144\" height=\"574\" fill=\"#020202\"/>\n    <rect x=\"782\" y=\"114\" width=\"390\" height=\"411\" fill=\"url(#diagonal)\"/>\n  </g>\n  <rect x=\"28.5\" y=\"28.5\" width=\"1143\" height=\"573\" fill=\"none\" stroke=\"#323232\"/>\n  <path d=\"M28 114.5h1144M28 525.5h1144M781.5 114v411\" fill=\"none\" stroke=\"#303030\"/>\n\n  <g transform=\"translate(71 51)\">\n    <rect width=\"11\" height=\"11\" rx=\"1\" fill=\"#f5f5f4\"/><rect x=\"15\" width=\"28\" height=\"11\" rx=\"1\" fill=\"#f5f5f4\"/>\n    <rect y=\"15\" width=\"11\" height=\"11\" rx=\"1\" fill=\"#9b9b9b\"/><rect x=\"15\" y=\"15\" width=\"28\" height=\"11\" rx=\"1\" fill=\"#9b9b9b\"/>\n    <rect y=\"30\" width=\"11\" height=\"11\" rx=\"1\" fill=\"#5f5f5f\"/><rect x=\"15\" y=\"30\" width=\"20\" height=\"11\" rx=\"1\" fill=\"#5f5f5f\"/>\n    <text x=\"61\" y=\"24\" class=\"mono bright\" font-size=\"24\" font-weight=\"550\">FARM<tspan fill=\"#777\">.JS</tspan></text>\n    <text x=\"61\" y=\"43\" class=\"label\">BY FARMING LABS</text>\n  </g>\n  <text x=\"1134\" y=\"72\" class=\"label\" text-anchor=\"end\">${escapeXml(brand)} · DOCUMENTATION</text>\n\n  <text x=\"71\" y=\"198\" class=\"mono bright\" font-size=\"13\" font-weight=\"650\">DOCS</text>\n  <line x1=\"117\" y1=\"193\" x2=\"155\" y2=\"193\" stroke=\"#696969\"/>\n  <text x=\"166\" y=\"198\" class=\"mono\" fill=\"#9b9b9b\" font-size=\"13\">${escapeXml(section)}</text>\n  ${renderTextLines(titleLines, 71, titleY, titleLineHeight, `class=\"pixel bright\" font-size=\"${titleSize}\" font-weight=\"500\" letter-spacing=\"-2.4\"`)}\n  ${renderTextLines(descriptionLines, 71, descriptionY, 29, 'class=\"sans\" fill=\"#a3a3a3\" font-size=\"20\" font-weight=\"430\" letter-spacing=\"-.3\"')}\n  <rect x=\"71\" y=\"${routeY}\" width=\"${Math.min(390, 56 + route.length * 8)}\" height=\"36\" fill=\"#050505\" stroke=\"#3c3c3c\"/>\n  <text x=\"85\" y=\"${routeY + 23}\" class=\"mono bright\" font-size=\"11\" font-weight=\"600\">GET</text>\n  <text x=\"119\" y=\"${routeY + 23}\" class=\"mono\" fill=\"#898989\" font-size=\"11\">${escapeXml(route)}</text>\n\n  ${renderIllustration(descriptor.illustration)}\n\n  <text x=\"71\" y=\"570\" class=\"mono bright\" font-size=\"13\" font-weight=\"550\">${escapeXml(footerUrl)}</text>\n  <text x=\"1134\" y=\"570\" class=\"mono\" fill=\"#9b9b9b\" font-size=\"12\" text-anchor=\"end\">FARM.JS DOCUMENTATION</text>\n  <path d=\"M20 20h10M20 20v10M1180 20h-10M1180 20v10M20 610h10M20 610v-10M1180 610h-10M1180 610v-10\" fill=\"none\" stroke=\"#9b9b9b\"/>\n</svg>`;\n}\n\nexport function renderFarmDocsSocialMetadata(\n  descriptor: FarmDocsSocialImageDescriptor,\n  customImage?: string,\n): string {\n  const imageUrl = customImage\n    ? new URL(customImage, descriptor.pageUrl).href\n    : descriptor.imageUrl;\n  const customExtension = customImage?.toLowerCase().split(/[?#]/, 1)[0];\n  const imageType = customExtension?.endsWith(\".webp\")\n    ? \"image/webp\"\n    : customExtension?.endsWith(\".png\")\n      ? \"image/png\"\n      : customExtension?.match(/\\.jpe?g$/)\n        ? \"image/jpeg\"\n        : \"image/svg+xml\";\n  const tag = (property: string, content: string, name = false) =>\n    `<meta ${name ? \"name\" : \"property\"}=\"${property}\" content=\"${escapeXml(content)}\">`;\n\n  return [\n    tag(\"og:type\", \"article\"),\n    tag(\"og:site_name\", descriptor.siteName),\n    tag(\"og:title\", descriptor.title),\n    tag(\"og:description\", descriptor.description),\n    tag(\"og:url\", descriptor.pageUrl),\n    tag(\"og:image\", imageUrl),\n    tag(\"og:image:type\", imageType),\n    ...(customImage\n      ? []\n      : [\n          tag(\"og:image:width\", String(FARM_DOCS_SOCIAL_IMAGE_WIDTH)),\n          tag(\"og:image:height\", String(FARM_DOCS_SOCIAL_IMAGE_HEIGHT)),\n        ]),\n    tag(\"og:image:alt\", descriptor.imageAlt),\n    tag(\"twitter:card\", \"summary_large_image\", true),\n    tag(\"twitter:title\", descriptor.title, true),\n    tag(\"twitter:description\", descriptor.description, true),\n    tag(\"twitter:image\", imageUrl, true),\n    tag(\"twitter:image:alt\", descriptor.imageAlt, true),\n  ].join(\"\\n  \");\n}\n","import type { FarmLayoutFonts } from \"../font\";\nimport { resolveFarmDocsContentDir } from \"./handler\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\ninterface FarmDocsAdapterServerModule {\n  createFarmDocsRuntimeHandler?: (\n    config: Record<string, unknown>,\n    options: {\n      rootDir: string;\n      clientEntry: string;\n      stylesheets: string[];\n      resolveLayoutFonts?: (\n        pathname: string,\n      ) => FarmLayoutFonts | undefined | Promise<FarmLayoutFonts | undefined>;\n      loadReactModule?: () => Promise<any>;\n    },\n  ) => (request: Request) => Promise<Response | null>;\n}\n\nexport interface FarmDocsAdapterHandlerOptions {\n  root: string;\n  srcDir?: string;\n  clientEntry: string;\n  fontStylesheetHref?: string;\n  globalStylesheetHref?: string;\n  resolveLayoutFonts?: (\n    pathname: string,\n  ) => FarmLayoutFonts | undefined | Promise<FarmLayoutFonts | undefined>;\n  loadModule: (specifier: string) => Promise<any>;\n}\n\nexport function hasFarmDocsRuntimeAdapter(\n  docs: FarmDocsResolvedConfig | undefined,\n): docs is FarmDocsResolvedConfig & { adapter: NonNullable<FarmDocsResolvedConfig[\"adapter\"]> } {\n  return Boolean(docs?.enabled && docs.adapter?.server && docs.adapter.react);\n}\n\n/**\n * Load a documentation runtime through the versioned adapter descriptor.\n *\n * Core deliberately knows nothing about the adapter's DOM or theme. It only\n * supplies host assets and Vite's module loader; the adapter returns the final\n * Web Request handler.\n */\nexport async function createFarmDocsAdapterHandler(\n  docs: FarmDocsResolvedConfig,\n  options: FarmDocsAdapterHandlerOptions,\n): Promise<(request: Request) => Promise<Response | null>> {\n  if (!hasFarmDocsRuntimeAdapter(docs)) {\n    throw new Error(\"Farm docs adapter requires server and react runtime entrypoints.\");\n  }\n\n  const serverModule = (await options.loadModule(\n    docs.adapter.server,\n  )) as FarmDocsAdapterServerModule;\n  if (typeof serverModule.createFarmDocsRuntimeHandler !== \"function\") {\n    const adapterId = JSON.stringify(docs.adapter.id);\n    const serverEntry = JSON.stringify(docs.adapter.server);\n    throw new Error(\n      `Farm docs adapter ${adapterId} does not export createFarmDocsRuntimeHandler from ${serverEntry}. ` +\n        \"Upgrade the adapter to a runtime-enabled release.\",\n    );\n  }\n\n  const runtimeConfig = {\n    ...docs.config,\n    entry: docs.config.entry || docs.entry.replace(/^\\/+|\\/+$/g, \"\") || \"docs\",\n    docsPath: docs.entry,\n    contentDir: resolveFarmDocsContentDir(docs, {\n      root: options.root,\n      srcDir: options.srcDir,\n    }),\n  };\n\n  return serverModule.createFarmDocsRuntimeHandler(runtimeConfig as Record<string, unknown>, {\n    rootDir: options.root,\n    clientEntry: options.clientEntry,\n    stylesheets: [options.fontStylesheetHref, options.globalStylesheetHref].filter(\n      (value): value is string => typeof value === \"string\" && value.length > 0,\n    ),\n    resolveLayoutFonts: options.resolveLayoutFonts,\n    loadReactModule: () => options.loadModule(docs.adapter.react!),\n  });\n}\n","import {\n  buildDocsAgentDiscoverySpec,\n  buildDocsConfigMap,\n  buildDocsDiagnostics as buildFarmingDocsDiagnostics,\n  buildDocsSitemapManifest,\n  performDocsSearch,\n  renderDocsAgentsDocument,\n  renderDocsLlmsTxt,\n  renderDocsMarkdownDocument,\n  renderDocsRobotsTxt,\n  renderDocsSitemapMarkdown,\n  renderDocsSitemapXml,\n  renderDocsSkillDocument,\n  type DocsConfig,\n  type DocsLlmsTxtPageInput,\n  type DocsSearchSourcePage,\n  type DocsSitemapPageInput,\n} from \"@farming-labs/docs\";\nimport { resolveDocsConfig } from \"../config\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./types\";\nimport {\n  discoverFarmDocsPages,\n  type LoadedFarmDocsPage,\n  loadFarmDocsPage,\n  resolveFarmDocsContentDir,\n  toFarmDocsMarkdownPage,\n} from \"./handler\";\n\nexport interface FarmDocsAPIOptions {\n  rootDir?: string;\n  root?: string;\n  srcDir?: string;\n  docs?: FarmDocsUserConfig | FarmDocsResolvedConfig;\n  config?: Partial<DocsConfig>;\n  configPath?: string;\n  entry?: string;\n  docsPath?: string;\n  contentDir?: string;\n}\n\nexport interface FarmDocsCloudRouteOptions {\n  locale?: string;\n  publicBaseUrl?: string;\n}\n\nexport interface FarmDocsCloudServer {\n  handleRequest(request: Request, options?: FarmDocsCloudRouteOptions): Promise<Response>;\n}\n\nexport type FarmDocsCloudIntegration =\n  | FarmDocsCloudServer\n  | (FarmDocsCloudRouteOptions & { docsCloud?: FarmDocsCloudServer });\n\nexport interface FarmDocsAPIRouteHandlers {\n  GET(request: Request): Promise<Response>;\n  POST(request: Request): Promise<Response>;\n}\n\nexport type FarmDocsAPIHandler = (request: Request) => Promise<Response | null>;\n\ninterface FarmDocsAPIContext {\n  root: string;\n  srcDir: string;\n  docs: FarmDocsResolvedConfig;\n  contentDir: string;\n}\n\ntype JsonRecord = Record<string, unknown>;\ntype DocsAPIPathTarget = {\n  format?: string;\n  slug?: string;\n};\ntype FarmDocsRuntimeConfig = {\n  root?: string;\n  srcDir?: string;\n  docs?: FarmDocsResolvedConfig;\n};\n\ndeclare global {\n  // Injected by Farm's generated server entry so route wrappers can stay zero-config.\n  // eslint-disable-next-line no-var\n  var __FARM_DOCS_RUNTIME_CONFIG__: FarmDocsRuntimeConfig | undefined;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isResolvedDocsConfig(value: unknown): value is FarmDocsResolvedConfig {\n  return (\n    isRecord(value) &&\n    typeof value.enabled === \"boolean\" &&\n    typeof value.entry === \"string\" &&\n    isRecord(value.config)\n  );\n}\n\nexport function isFarmDocsAPIRequest(requestOrPathname: Request | string): boolean {\n  const pathname =\n    typeof requestOrPathname === \"string\"\n      ? requestOrPathname\n      : new URL(requestOrPathname.url).pathname;\n\n  return pathname === \"/api/docs\" || pathname.startsWith(\"/api/docs/\");\n}\n\nfunction json(data: unknown, init: ResponseInit = {}): Response {\n  const headers = new Headers(init.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json\");\n  }\n  return new Response(JSON.stringify(data), { ...init, headers });\n}\n\nfunction text(content: string, contentType: string, init: ResponseInit = {}): Response {\n  const headers = new Headers(init.headers);\n  headers.set(\"Content-Type\", contentType);\n  return new Response(content, { ...init, headers });\n}\n\nfunction omitHeadBody(response: Response): Response {\n  return new Response(null, {\n    status: response.status,\n    statusText: response.statusText,\n    headers: response.headers,\n  });\n}\n\nfunction normalizeAction(value: string | null | undefined): string | undefined {\n  return value?.trim().toLowerCase().replace(/_/g, \"-\") || undefined;\n}\n\nfunction getDocsTitle(docs: FarmDocsResolvedConfig): string {\n  return typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n    ? String((docs.config.nav as { title?: unknown }).title || \"Documentation\")\n    : \"Documentation\";\n}\n\nfunction isDocsCloudServer(value: unknown): value is FarmDocsCloudServer {\n  return isRecord(value) && typeof value.handleRequest === \"function\";\n}\n\nfunction resolveDocsCloudIntegration(\n  integration?: FarmDocsCloudIntegration,\n): { docsCloud: FarmDocsCloudServer; routeOptions: FarmDocsCloudRouteOptions } | undefined {\n  if (!integration) return undefined;\n\n  if (isDocsCloudServer(integration)) {\n    return { docsCloud: integration, routeOptions: {} };\n  }\n\n  if (!integration.docsCloud) return undefined;\n\n  return {\n    docsCloud: integration.docsCloud,\n    routeOptions: {\n      locale: integration.locale,\n      publicBaseUrl: integration.publicBaseUrl,\n    },\n  };\n}\n\nfunction isDocsCloudGetRequest(request: Request): boolean {\n  const url = new URL(request.url);\n  const cloud = normalizeAction(url.searchParams.get(\"cloud\"));\n  const action = normalizeAction(url.searchParams.get(\"action\"));\n  const format = normalizeAction(url.searchParams.get(\"format\"));\n\n  return (\n    cloud === \"config\" ||\n    cloud === \"public-config\" ||\n    action === \"cloud-config\" ||\n    action === \"docs-cloud-config\" ||\n    format === \"cloud-config\" ||\n    format === \"docs-cloud-config\"\n  );\n}\n\nfunction isDocsCloudAction(action: string | undefined): boolean {\n  return Boolean(\n    action &&\n    [\"analytics\", \"track\", \"track-event\", \"event\", \"ask-ai\", \"ai\", \"chat\", \"docs-cloud\"].includes(\n      action,\n    ),\n  );\n}\n\nasync function readJson(request: Request): Promise<unknown> {\n  try {\n    return await request.clone().json();\n  } catch {\n    return undefined;\n  }\n}\n\nasync function isDocsCloudPostRequest(request: Request): Promise<boolean> {\n  const url = new URL(request.url);\n  const cloud = normalizeAction(url.searchParams.get(\"cloud\"));\n  const action = normalizeAction(url.searchParams.get(\"action\"));\n\n  if (isDocsCloudAction(cloud) || isDocsCloudAction(action)) return true;\n\n  const body = await readJson(request);\n  if (!isRecord(body)) return false;\n\n  const bodyAction = normalizeAction(typeof body.action === \"string\" ? body.action : undefined);\n  if (isDocsCloudAction(bodyAction)) return true;\n\n  if (typeof body.type === \"string\") return true;\n  if (isRecord(body.event) && typeof body.event.type === \"string\") return true;\n  if (isRecord(body.payload) && typeof body.payload.type === \"string\") return true;\n\n  return false;\n}\n\nfunction normalizeDocsApiSlug(\n  value: string | null | undefined,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const entry = docs.entry.replace(/^\\/+|\\/+$/g, \"\");\n  let slug = (value || \"\").trim().replace(/^\\/+|\\/+$/g, \"\");\n\n  if (entry && slug === entry) return \"\";\n  if (entry && slug.startsWith(`${entry}/`)) {\n    slug = slug.slice(entry.length + 1);\n  }\n\n  let decoded = slug;\n  try {\n    decoded = decodeURIComponent(slug);\n  } catch {\n    // Malformed percent-encoding resolves to a non-matching slug (404),\n    // not an exception out of the handler.\n  }\n  return decoded.replace(/\\.(mdx?|markdown)$/i, \"\");\n}\n\nfunction getDocsAPIPathTarget(request: Request): DocsAPIPathTarget {\n  const pathname = new URL(request.url).pathname.replace(/\\/+$/, \"\") || \"/\";\n  const prefix = \"/api/docs\";\n\n  if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) return {};\n\n  const rawValue = pathname === prefix ? \"\" : pathname.slice(prefix.length + 1);\n  const value = rawValue.replace(/^\\/+|\\/+$/g, \"\");\n  const normalizedValue = normalizeAction(value);\n\n  if (!value) return {};\n  if (\n    normalizedValue === \"agent\" ||\n    normalizedValue === \"agent.json\" ||\n    normalizedValue === \"agent/spec\"\n  ) {\n    return { format: \"agent-spec\" };\n  }\n  if (\n    normalizedValue === \"agents\" ||\n    normalizedValue === \"agents.md\" ||\n    normalizedValue === \"agent.md\"\n  ) {\n    return { format: \"agents\" };\n  }\n  if (normalizedValue === \"skill\" || normalizedValue === \"skill.md\") return { format: \"skill\" };\n  if (normalizedValue === \"llms.txt\") return { format: \"llms\" };\n  if (normalizedValue === \"llms-full.txt\") return { format: \"llms-full\" };\n  if (normalizedValue === \"sitemap.md\") return { format: \"sitemap-md\" };\n  if (normalizedValue === \"sitemap.xml\") return { format: \"sitemap-xml\" };\n  if (normalizedValue === \"robots.txt\") return { format: \"robots\" };\n  if (/\\.(mdx?|markdown)$/i.test(value)) return { format: \"markdown\", slug: value };\n\n  return { slug: value };\n}\n\nfunction getDocsAPIFormat(request: Request): string | undefined {\n  const url = new URL(request.url);\n  return (\n    normalizeAction(url.searchParams.get(\"format\") || url.searchParams.get(\"type\")) ||\n    getDocsAPIPathTarget(request).format\n  );\n}\n\nfunction getDocsDescription(docs: FarmDocsResolvedConfig): string | undefined {\n  return docs.config.metadata?.description;\n}\n\nfunction getLoadedDocsPages(context: FarmDocsAPIContext): LoadedFarmDocsPage[] {\n  return discoverFarmDocsPages(context.contentDir, context.docs)\n    .map((page) => loadFarmDocsPage(context.contentDir, context.docs, page.slug))\n    .filter((page): page is LoadedFarmDocsPage => Boolean(page));\n}\n\nfunction toDocsSourcePage(page: LoadedFarmDocsPage): DocsSearchSourcePage {\n  return {\n    ...toFarmDocsMarkdownPage(page),\n    sourcePath: page.sourcePath,\n  };\n}\n\nfunction toDocsSitemapPage(page: LoadedFarmDocsPage): DocsSitemapPageInput {\n  return {\n    ...toFarmDocsMarkdownPage(page),\n    sourcePath: page.sourcePath,\n  };\n}\n\nfunction toDocsLlmsPage(page: LoadedFarmDocsPage): DocsLlmsTxtPageInput {\n  return toFarmDocsMarkdownPage(page);\n}\n\nfunction getDocsLlmsOptions(context: FarmDocsAPIContext, request: Request) {\n  const configured = isRecord(context.docs.config.llmsTxt) ? context.docs.config.llmsTxt : {};\n  return {\n    enabled: true,\n    baseUrl: new URL(request.url).origin,\n    siteTitle: getDocsTitle(context.docs),\n    siteDescription: getDocsDescription(context.docs),\n    ...configured,\n  };\n}\n\nfunction getDocsDiscoveryOptions(context: FarmDocsAPIContext, request: Request) {\n  const origin = new URL(request.url).origin;\n\n  return {\n    origin,\n    entry: context.docs.entry,\n    i18n: null,\n    search: context.docs.config.search ?? true,\n    mcp: {\n      enabled: false,\n      route: \"/api/docs/mcp\",\n      name: `${getDocsTitle(context.docs)} MCP`,\n      version: \"1\",\n      tools: {\n        listDocs: false,\n        listPages: false,\n        readPage: false,\n        searchDocs: false,\n        getNavigation: false,\n        getCodeExamples: false,\n        getConfigSchema: false,\n      },\n    },\n    feedback: undefined,\n    llms: getDocsLlmsOptions(context, request),\n    sitemap: context.docs.config.sitemap ?? true,\n    robots: context.docs.config.robots ?? true,\n    openapi: context.docs.config.apiReference,\n    markdown: {\n      acceptHeader: true,\n      signatureAgentHeader: true,\n    },\n  };\n}\n\nfunction buildSitemapManifest(context: FarmDocsAPIContext, request: Request) {\n  const origin = new URL(request.url).origin;\n  return buildDocsSitemapManifest({\n    pages: getLoadedDocsPages(context).map(toDocsSitemapPage),\n    entry: context.docs.entry,\n    siteTitle: getDocsTitle(context.docs),\n    baseUrl: origin,\n  });\n}\n\nfunction renderLlmsTxt(context: FarmDocsAPIContext, request: Request, full: boolean): string {\n  const generated = renderDocsLlmsTxt(\n    getLoadedDocsPages(context).map(toDocsLlmsPage),\n    getDocsLlmsOptions(context, request),\n  );\n\n  return full ? generated.llmsFullTxt : generated.llmsTxt;\n}\n\nfunction renderSkillDocument(context: FarmDocsAPIContext, request: Request): string {\n  const farmAliases = [\n    \"## Farm API Route Aliases\",\n    \"\",\n    \"- Search JSON: /api/docs?query=<term>\",\n    \"- Config JSON: /api/docs?format=config\",\n    \"- Markdown by query: /api/docs?format=markdown&path=<slug>\",\n    \"- Markdown by path: /api/docs/<slug>.md\",\n    \"- LLM summary: /api/docs?format=llms\",\n    \"- Full LLM document: /api/docs?format=llms-full\",\n    \"- Sitemap XML: /api/docs?format=sitemap-xml\",\n    \"- Agent spec JSON: /api/docs/agent/spec\",\n  ].join(\"\\n\");\n\n  return `${renderDocsSkillDocument(getDocsDiscoveryOptions(context, request)).trim()}\\n\\n${farmAliases}\\n`;\n}\n\nfunction renderAgentsDocument(context: FarmDocsAPIContext, request: Request): string {\n  return `${renderDocsAgentsDocument(getDocsDiscoveryOptions(context, request)).trim()}\\n`;\n}\n\nfunction buildAgentSpec(context: FarmDocsAPIContext, request: Request) {\n  const url = new URL(request.url);\n  const origin = url.origin;\n  const pages = discoverFarmDocsPages(context.contentDir, context.docs);\n  const spec = buildDocsAgentDiscoverySpec(getDocsDiscoveryOptions(context, request));\n  const title = getDocsTitle(context.docs);\n\n  return {\n    ...spec,\n    name: title,\n    site: {\n      ...spec.site,\n      title,\n      description: getDocsDescription(context.docs),\n      entry: context.docs.entry,\n    },\n    entry: context.docs.entry,\n    routes: {\n      docs: `${origin}${context.docs.entry}`,\n      config: `${origin}/api/docs?format=config`,\n      search: `${origin}/api/docs?query=<term>`,\n      markdown: `${origin}/api/docs/<slug>.md`,\n      markdownQuery: `${origin}/api/docs?format=markdown&path=<slug>`,\n      llms: `${origin}/api/docs?format=llms`,\n      llmsFull: `${origin}/api/docs?format=llms-full`,\n      sitemapXml: `${origin}/api/docs?format=sitemap-xml`,\n      sitemapMarkdown: `${origin}/api/docs?format=sitemap-md`,\n      robots: `${origin}/api/docs?format=robots`,\n      skill: `${origin}/api/docs?format=skill`,\n      agents: `${origin}/api/docs?format=agents`,\n      agentSpec: `${origin}/api/docs/agent/spec`,\n    },\n    capabilities: {\n      ...spec.capabilities,\n      search: spec.capabilities.search,\n      markdown: spec.capabilities.markdownRoutes,\n      llms: spec.capabilities.llms,\n      sitemap: spec.capabilities.sitemap,\n      robots: spec.capabilities.robots,\n      post: false,\n    },\n    pages,\n  };\n}\n\nfunction buildDiagnostics(context: FarmDocsAPIContext) {\n  const pages = discoverFarmDocsPages(context.contentDir, context.docs);\n  const diagnostics = buildFarmingDocsDiagnostics(context.docs.config, {\n    entry: context.docs.entry,\n    mcp: {\n      enabled: false,\n      route: \"/api/docs/mcp\",\n      name: `${getDocsTitle(context.docs)} MCP`,\n      version: \"1\",\n      tools: {\n        listDocs: false,\n        listPages: false,\n        readPage: false,\n        searchDocs: false,\n        getNavigation: false,\n        getCodeExamples: false,\n        getConfigSchema: false,\n      },\n    },\n  });\n\n  return {\n    ...diagnostics,\n    enabled: context.docs.enabled,\n    entry: context.docs.entry,\n    root: context.root,\n    srcDir: context.srcDir,\n    contentDir: context.contentDir,\n    configPath: context.docs.configPath || null,\n    pageCount: pages.length,\n    pages,\n  };\n}\n\nasync function searchDocs(context: FarmDocsAPIContext, request: Request, query: string) {\n  const loadedPages = getLoadedDocsPages(context);\n  const sourcePages = loadedPages.map(toDocsSourcePage);\n  const sourcePageByUrl = new Map(sourcePages.map((page) => [page.url, page]));\n  const resultLimit =\n    isRecord(context.docs.config.search) &&\n    typeof context.docs.config.search.maxResults === \"number\"\n      ? context.docs.config.search.maxResults\n      : undefined;\n\n  const results = await performDocsSearch({\n    pages: sourcePages,\n    query,\n    search: context.docs.config.search ?? true,\n    pathname: new URL(request.url).pathname,\n    siteTitle: getDocsTitle(context.docs),\n    limit: resultLimit,\n  });\n\n  return results.map((result) => {\n    const pageUrl = result.url.split(\"#\")[0];\n    const page = sourcePageByUrl.get(pageUrl);\n    return {\n      ...result,\n      title: page?.title || result.content,\n      href: page?.url || pageUrl,\n      description: result.description || page?.description,\n    };\n  });\n}\n\nasync function resolveAPIContext(options: FarmDocsAPIOptions): Promise<FarmDocsAPIContext> {\n  const runtimeConfig = globalThis.__FARM_DOCS_RUNTIME_CONFIG__;\n  const root = options.rootDir || options.root || runtimeConfig?.root || process.cwd();\n  const srcDir = options.srcDir || runtimeConfig?.srcDir || \"src\";\n  const canUseRuntimeDocs =\n    options.docs === undefined &&\n    options.config === undefined &&\n    options.configPath === undefined &&\n    options.entry === undefined &&\n    options.docsPath === undefined &&\n    options.contentDir === undefined &&\n    options.root === undefined &&\n    options.rootDir === undefined &&\n    options.srcDir === undefined;\n  const docsInput =\n    options.docs ??\n    (canUseRuntimeDocs ? runtimeConfig?.docs : undefined) ??\n    ({\n      enabled: true,\n      entry: options.entry,\n      docsPath: options.docsPath,\n      contentDir: options.contentDir,\n      config: options.config,\n      configPath: options.configPath,\n    } satisfies Exclude<FarmDocsUserConfig, boolean>);\n  const docs = isResolvedDocsConfig(docsInput)\n    ? docsInput\n    : await resolveDocsConfig(docsInput, { root, srcDir });\n\n  return {\n    root,\n    srcDir,\n    docs,\n    contentDir: resolveFarmDocsContentDir(docs, { root, srcDir }),\n  };\n}\n\nasync function handleDocsAPIGet(request: Request, context: FarmDocsAPIContext): Promise<Response> {\n  if (!context.docs.enabled) {\n    return json({ error: \"Docs are disabled\" }, { status: 404 });\n  }\n\n  const url = new URL(request.url);\n  const format = getDocsAPIFormat(request);\n  const pathTarget = getDocsAPIPathTarget(request);\n\n  if (format === \"config\" || format === \"docs-config\") {\n    return json({\n      entry: context.docs.entry,\n      contentDir: context.docs.contentDir || context.docs.config.contentDir || null,\n      config: context.docs.config,\n      map: buildDocsConfigMap(context.docs.config, {\n        file: context.docs.configPath || \"farm.config.ts\",\n      }),\n    });\n  }\n\n  if (format === \"skill\")\n    return text(renderSkillDocument(context, request), \"text/markdown; charset=utf-8\");\n  if (format === \"agents\")\n    return text(renderAgentsDocument(context, request), \"text/markdown; charset=utf-8\");\n  if (format === \"agent\" || format === \"agent-spec\") return json(buildAgentSpec(context, request));\n  if (format === \"diagnostics\") return json(buildDiagnostics(context));\n  if (format === \"llms\")\n    return text(renderLlmsTxt(context, request, false), \"text/plain; charset=utf-8\");\n  if (format === \"llms-full\")\n    return text(renderLlmsTxt(context, request, true), \"text/plain; charset=utf-8\");\n  if (format === \"sitemap-md\") {\n    return text(\n      renderDocsSitemapMarkdown(buildSitemapManifest(context, request), {\n        includeDescriptions: true,\n      }),\n      \"text/markdown; charset=utf-8\",\n    );\n  }\n  if (format === \"sitemap-xml\" || format === \"sitemap\") {\n    const origin = new URL(request.url).origin;\n    return text(\n      renderDocsSitemapXml(buildSitemapManifest(context, request), {\n        baseUrl: origin,\n        includeLastmod: true,\n      }),\n      \"application/xml; charset=utf-8\",\n    );\n  }\n  if (format === \"robots\") {\n    return text(\n      renderDocsRobotsTxt({\n        entry: context.docs.entry,\n        sitemap: context.docs.config.sitemap ?? true,\n        robots: context.docs.config.robots ?? true,\n        baseUrl: new URL(request.url).origin,\n      }),\n      \"text/plain; charset=utf-8\",\n    );\n  }\n\n  if (format === \"markdown\" || url.pathname.endsWith(\".md\")) {\n    const pathParam = url.searchParams.get(\"path\") || url.searchParams.get(\"slug\");\n    const slug = normalizeDocsApiSlug(pathParam ?? pathTarget.slug ?? \"\", context.docs);\n    const page = loadFarmDocsPage(context.contentDir, context.docs, slug);\n    if (!page) return text(\"Docs page not found\\n\", \"text/plain; charset=utf-8\", { status: 404 });\n    return text(\n      renderDocsMarkdownDocument(toFarmDocsMarkdownPage(page), {\n        origin: new URL(request.url).origin,\n        llms: getDocsLlmsOptions(context, request),\n        sitemap: context.docs.config.sitemap,\n      }),\n      \"text/markdown; charset=utf-8\",\n    );\n  }\n\n  const query = url.searchParams.get(\"query\") || url.searchParams.get(\"q\") || \"\";\n  if (!query.trim()) return json([]);\n  return json(await searchDocs(context, request, query));\n}\n\nexport function createDocsAPI(\n  options: FarmDocsAPIOptions = {},\n  cloudIntegration?: FarmDocsCloudIntegration,\n): FarmDocsAPIRouteHandlers {\n  let contextPromise: Promise<FarmDocsAPIContext> | undefined;\n  const getContext = () => {\n    contextPromise ??= resolveAPIContext(options);\n    return contextPromise;\n  };\n  const integration = resolveDocsCloudIntegration(cloudIntegration);\n\n  return {\n    async GET(request: Request) {\n      if (integration && isDocsCloudGetRequest(request)) {\n        return integration.docsCloud.handleRequest(request, integration.routeOptions);\n      }\n\n      return handleDocsAPIGet(request, await getContext());\n    },\n    async POST(request: Request) {\n      if (integration && (await isDocsCloudPostRequest(request))) {\n        return integration.docsCloud.handleRequest(request, integration.routeOptions);\n      }\n\n      return json(\n        {\n          error: \"AI is not enabled for this Farm docs API route yet.\",\n        },\n        { status: 501 },\n      );\n    },\n  };\n}\n\nexport function createFarmDocsAPIHandler(\n  options: FarmDocsAPIOptions = {},\n  cloudIntegration?: FarmDocsCloudIntegration,\n): FarmDocsAPIHandler {\n  const handlers = createDocsAPI(options, cloudIntegration);\n\n  return async function handleFarmDocsAPIRequest(request: Request): Promise<Response | null> {\n    if (!isFarmDocsAPIRequest(request)) return null;\n\n    const method = request.method.toUpperCase();\n    if (method === \"GET\" || method === \"HEAD\") {\n      const response = await handlers.GET(request);\n      return method === \"HEAD\" ? omitHeadBody(response) : response;\n    }\n    if (method === \"POST\") {\n      return handlers.POST(request);\n    }\n\n    return json(\n      {\n        error: \"Method Not Allowed\",\n      },\n      {\n        status: 405,\n        headers: {\n          Allow: \"GET, HEAD, POST\",\n        },\n      },\n    );\n  };\n}\n","export type FarmIntegrationAPIMethod =\n  | \"GET\"\n  | \"QUERY\"\n  | \"POST\"\n  | \"PUT\"\n  | \"PATCH\"\n  | \"DELETE\"\n  | \"OPTIONS\"\n  | \"HEAD\";\n\nexport type FarmIntegrationAPIBodyFormat = \"json\" | \"form\" | \"none\";\nexport type FarmIntegrationAPIResponseFormat = \"json\" | \"text\" | \"response\";\n\nexport interface FarmIntegrationAPIOperation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n> {\n  readonly kind: \"farm-integration-api-operation\";\n  path: string;\n  method: TMethod;\n  bodyFormat?: FarmIntegrationAPIBodyFormat;\n  responseFormat?: FarmIntegrationAPIResponseFormat;\n  headers?: Record<string, string>;\n  credentials?: RequestCredentials;\n  isServer?: TServer;\n  __pathless?: boolean;\n  __types?: {\n    body: TBody;\n    query: TQuery;\n    response: TResponse;\n  };\n}\n\nexport type FarmIntegrationAPI = {\n  [key: string]: FarmIntegrationAPI | FarmIntegrationAPIOperation<any, any, any, any, any>;\n};\n\nexport type FarmIntegrationRouteOperationCarrier<\n  TPath extends string = string,\n  TOperation extends FarmIntegrationAPIOperation<any, any, any, any, any> =\n    FarmIntegrationAPIOperation<any, any, any, any, any>,\n> = {\n  path: TPath;\n  __operation: TOperation;\n};\n\ntype IntegrationAPIBuilderOptions<TServer extends boolean = false> = Omit<\n  FarmIntegrationAPIOperation<any, any, any, TServer>,\n  \"kind\" | \"method\" | \"path\" | \"__pathless\" | \"__types\"\n>;\n\nexport function defineIntegrationAPIOperation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n>(\n  operation: Omit<\n    FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>,\n    \"kind\" | \"__types\"\n  >,\n): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod> {\n  return {\n    kind: \"farm-integration-api-operation\",\n    ...operation,\n  };\n}\n\nexport function defineIntegrationAPI<TAPI extends FarmIntegrationAPI>(api: TAPI): TAPI {\n  return api;\n}\n\nfunction operation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n>(\n  method: TMethod,\n  pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n  maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod> {\n  const hasExplicitPath = typeof pathOrOptions === \"string\";\n  const path = hasExplicitPath ? pathOrOptions : \"\";\n  const options = (\n    hasExplicitPath\n      ? maybeOptions\n      : {\n          ...maybeOptions,\n          ...pathOrOptions,\n        }\n  ) as IntegrationAPIBuilderOptions<TServer>;\n\n  return defineIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>({\n    path,\n    method,\n    __pathless: !hasExplicitPath,\n    ...options,\n  });\n}\n\nfunction get<TResponse = unknown, TServer extends boolean = false>(\n  path: string,\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, never, TResponse, TServer, \"GET\">;\nfunction get<TQuery = never, TResponse = unknown, TServer extends boolean = false>(\n  path: string,\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"GET\">;\nfunction get<TResponse = unknown, TServer extends boolean = false>(\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, never, TResponse, TServer, \"GET\">;\nfunction get<TQuery = never, TResponse = unknown, TServer extends boolean = false>(\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"GET\">;\nfunction get(\n  pathOrOptions?: string | IntegrationAPIBuilderOptions<boolean>,\n  maybeOptions: IntegrationAPIBuilderOptions<boolean> = {} as IntegrationAPIBuilderOptions<boolean>,\n) {\n  return operation<never, any, any, boolean>(\"GET\", pathOrOptions, maybeOptions);\n}\n\nfunction isOperation(value: unknown): value is FarmIntegrationAPIOperation<any, any, any, any> {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (value as FarmIntegrationAPIOperation<any, any, any, any>).kind ===\n      \"farm-integration-api-operation\"\n  );\n}\n\nfunction bindRoutePath<TAPI extends FarmIntegrationAPI>(path: string, api: TAPI): TAPI {\n  const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n    if (isOperation(value)) {\n      return [\n        key,\n        {\n          ...value,\n          path,\n          __pathless: false,\n        },\n      ];\n    }\n\n    if (value && typeof value === \"object\") {\n      return [key, bindRoutePath(path, value as FarmIntegrationAPI)];\n    }\n\n    return [key, value];\n  });\n\n  return Object.fromEntries(entries) as TAPI;\n}\n\ntype RouteOperationsToAPI<\n  TOperations extends readonly FarmIntegrationAPIOperation<any, any, any, any, any>[],\n> = {\n  [TMethod in Lowercase<TOperations[number][\"method\"] & string>]: Extract<\n    TOperations[number],\n    { method: Uppercase<TMethod> }\n  >;\n};\n\ntype StripRouteClientPrefix<TPath extends string> = TPath extends `/api/${string}/${infer TRest}`\n  ? TRest\n  : TPath extends `/${string}/${infer TRest}`\n    ? TRest\n    : TPath extends `/${infer TRest}`\n      ? TRest\n      : TPath;\n\ntype NormalizeRouteSegment<TSegment extends string> = TSegment extends `[...${infer TName}]`\n  ? TName\n  : TSegment extends `[${infer TName}]`\n    ? TName\n    : TSegment extends `${infer TName}(${string}`\n      ? TName\n      : CamelCaseRouteSegment<TSegment>;\n\ntype CamelCaseRouteSegment<TSegment extends string> =\n  TSegment extends `${infer THead}-${infer TTail}`\n    ? `${THead}${Capitalize<CamelCaseRouteSegment<TTail>>}`\n    : TSegment;\n\ntype RouteNamespaceFromPath<\n  TPath extends string,\n  TOperation extends FarmIntegrationAPIOperation<any, any, any, any, any>,\n> = TPath extends `${infer THead}/${infer TTail}`\n  ? {\n      [TKey in NormalizeRouteSegment<THead>]: RouteNamespaceFromPath<TTail, TOperation>;\n    }\n  : {\n      [TKey in NormalizeRouteSegment<TPath>]: {\n        [TMethod in Lowercase<TOperation[\"method\"] & string>]: TOperation;\n      };\n    };\n\ntype UnionToIntersection<TUnion> = (\n  TUnion extends unknown ? (value: TUnion) => void : never\n) extends (value: infer TIntersection) => void\n  ? TIntersection\n  : never;\n\ntype ExpandRecursively<TValue> = TValue extends (...args: any[]) => any\n  ? TValue\n  : TValue extends object\n    ? { [TKey in keyof TValue]: ExpandRecursively<TValue[TKey]> }\n    : TValue;\n\ntype RoutesToAPI<TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[]> =\n  ExpandRecursively<\n    UnionToIntersection<\n      TRoutes[number] extends FarmIntegrationRouteOperationCarrier<infer TPath, infer TOperation>\n        ? RouteNamespaceFromPath<StripRouteClientPrefix<TPath>, TOperation>\n        : never\n    >\n  >;\n\nexport type InferIntegrationAPIFromRoutes<\n  TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[],\n> = RoutesToAPI<TRoutes>;\n\nfunction route<TAPI extends FarmIntegrationAPI>(path: string, definition: TAPI): TAPI;\nfunction route<TOperations extends readonly FarmIntegrationAPIOperation<any, any, any, any, any>[]>(\n  path: string,\n  ...operations: TOperations\n): RouteOperationsToAPI<TOperations>;\nfunction route(\n  path: string,\n  definitionOrOperation: FarmIntegrationAPI | FarmIntegrationAPIOperation<any, any, any, any, any>,\n  ...operations: readonly FarmIntegrationAPIOperation<any, any, any, any, any>[]\n) {\n  if (isOperation(definitionOrOperation)) {\n    const allOperations = [definitionOrOperation, ...operations];\n    return Object.fromEntries(\n      allOperations.map((operation) => [\n        operation.method.toLowerCase(),\n        {\n          ...operation,\n          path,\n          __pathless: false,\n        },\n      ]),\n    );\n  }\n\n  return bindRoutePath(path, definitionOrOperation as FarmIntegrationAPI);\n}\n\nfunction normalizeRouteSegment(segment: string): string {\n  if (!segment) {\n    return \"index\";\n  }\n\n  if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n    return segment.slice(4, -1) || \"index\";\n  }\n\n  if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n    return segment.slice(1, -1) || \"index\";\n  }\n\n  const matcherIndex = segment.indexOf(\"(\");\n  if (matcherIndex > 0) {\n    return segment.slice(0, matcherIndex);\n  }\n\n  return camelCaseRouteSegment(segment);\n}\n\nfunction camelCaseRouteSegment(segment: string): string {\n  return segment.replace(/-([a-zA-Z0-9])/g, (_match, value: string) => value.toUpperCase());\n}\n\nfunction getRouteClientSegments(path: string): string[] {\n  const segments = path.split(\"/\").filter(Boolean);\n  if (segments.length === 0) {\n    return [\"index\"];\n  }\n\n  const stripped =\n    segments[0] === \"api\" && segments.length > 2\n      ? segments.slice(2)\n      : segments.length > 1\n        ? segments.slice(1)\n        : [segments[segments.length - 1]];\n\n  return stripped.map(normalizeRouteSegment).filter(Boolean);\n}\n\nfunction setRouteOperation(\n  target: Record<string, unknown>,\n  pathSegments: string[],\n  operation: FarmIntegrationAPIOperation<any, any, any, any, any>,\n) {\n  const [head, ...tail] = pathSegments;\n  if (!head) {\n    return;\n  }\n\n  if (tail.length === 0) {\n    const leaf = ((target[head] as Record<string, unknown> | undefined) || {}) as Record<\n      string,\n      unknown\n    >;\n    leaf[operation.method.toLowerCase()] = {\n      ...operation,\n      path: operation.path,\n      __pathless: false,\n    };\n    target[head] = leaf;\n    return;\n  }\n\n  const branch = ((target[head] as Record<string, unknown> | undefined) || {}) as Record<\n    string,\n    unknown\n  >;\n  target[head] = branch;\n  setRouteOperation(branch, tail, operation);\n}\n\nfunction fromRoutes<TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[]>(\n  routes: TRoutes,\n): RoutesToAPI<TRoutes> {\n  const definition: Record<string, unknown> = {};\n\n  for (const route of routes) {\n    if (!isOperation(route.__operation)) {\n      continue;\n    }\n\n    setRouteOperation(definition, getRouteClientSegments(route.path), {\n      ...route.__operation,\n      path: route.path,\n      __pathless: false,\n    });\n  }\n\n  return definition as RoutesToAPI<TRoutes>;\n}\n\nexport const api = {\n  get,\n  route,\n  fromRoutes,\n  query<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"QUERY\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"QUERY\">(\"QUERY\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  post<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"POST\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"POST\">(\"POST\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  put<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PUT\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"PUT\">(\"PUT\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  patch<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PATCH\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"PATCH\">(\"PATCH\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  delete<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"DELETE\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"DELETE\">(\"DELETE\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  options<TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"OPTIONS\"> {\n    return operation<never, TQuery, TResponse, TServer, \"OPTIONS\">(\n      \"OPTIONS\",\n      pathOrOptions,\n      maybeOptions,\n    );\n  },\n  head<TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"HEAD\"> {\n    return operation<never, TQuery, TResponse, TServer, \"HEAD\">(\n      \"HEAD\",\n      pathOrOptions,\n      maybeOptions,\n    );\n  },\n  form: {\n    query<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"QUERY\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"QUERY\">(\"QUERY\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    post<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"POST\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"POST\">(\"POST\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    put<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PUT\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"PUT\">(\"PUT\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    patch<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PATCH\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"PATCH\">(\"PATCH\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    delete<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"DELETE\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"DELETE\">(\"DELETE\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n  },\n};\n\nexport const endpoint = api;\n","/**\n * Decode a percent-encoded path segment, falling back to the raw value.\n *\n * Request paths are not guaranteed to be validly percent-encoded, so\n * `decodeURIComponent` can throw on input that is still a legal URL: a\n * latin-1 escape such as `caf%E9` from an old link, or a truncated `%ZZ`\n * from a crawler. A malformed segment simply will not match a known route,\n * which is a 404, so it must not throw out of route matching.\n */\nexport function decodeRouteSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n","type RequestContextCarrier = object;\n\nexport interface SetRequestContextOptions {\n  exposeToPage?: boolean;\n}\n\nexport interface RequestContextSnapshotOptions {\n  exposedOnly?: boolean;\n}\n\ninterface RequestContextBucket {\n  privateData: Map<string, any>;\n  exposedData: Map<string, any>;\n}\n\nconst REQUEST_CONTEXT_STORE_KEY = Symbol.for(\"farm.requestContextStore\");\n\ntype GlobalWithRequestContextStore = typeof globalThis & {\n  [REQUEST_CONTEXT_STORE_KEY]?: WeakMap<RequestContextCarrier, RequestContextBucket>;\n};\n\nfunction getRequestContextStore() {\n  const globalState = globalThis as GlobalWithRequestContextStore;\n  if (!globalState[REQUEST_CONTEXT_STORE_KEY]) {\n    globalState[REQUEST_CONTEXT_STORE_KEY] = new WeakMap<\n      RequestContextCarrier,\n      RequestContextBucket\n    >();\n  }\n\n  return globalState[REQUEST_CONTEXT_STORE_KEY]!;\n}\n\nfunction getBucket(target: RequestContextCarrier): RequestContextBucket {\n  const requestContextStore = getRequestContextStore();\n  let bucket = requestContextStore.get(target);\n  if (!bucket) {\n    bucket = {\n      privateData: new Map<string, any>(),\n      exposedData: new Map<string, any>(),\n    };\n    requestContextStore.set(target, bucket);\n  }\n  return bucket;\n}\n\nexport function setRequestContext(\n  target: RequestContextCarrier,\n  key: string,\n  value: any,\n  options: SetRequestContextOptions = {},\n): void {\n  const bucket = getBucket(target);\n  bucket.privateData.set(key, value);\n  if (options.exposeToPage) {\n    bucket.exposedData.set(key, value);\n  }\n}\n\nexport function getRequestContext<T = any>(\n  target: RequestContextCarrier,\n  key: string,\n): T | undefined {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  return bucket?.privateData.get(key) as T | undefined;\n}\n\nexport function hasRequestContext(target: RequestContextCarrier, key: string): boolean {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  return bucket?.privateData.has(key) ?? false;\n}\n\nexport function deleteRequestContext(target: RequestContextCarrier, key: string): boolean {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return false;\n  const removedPrivate = bucket.privateData.delete(key);\n  bucket.exposedData.delete(key);\n  return removedPrivate;\n}\n\nexport function clearRequestContext(target: RequestContextCarrier): void {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return;\n  bucket.privateData.clear();\n  bucket.exposedData.clear();\n}\n\nexport function getRequestContextSnapshot(\n  target: RequestContextCarrier,\n  options: RequestContextSnapshotOptions = {},\n): Map<string, any> {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return new Map<string, any>();\n  if (options.exposedOnly) {\n    return new Map(bucket.exposedData);\n  }\n  return new Map(bucket.privateData);\n}\n","import { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport { defineSchema } from \"./schema\";\nimport type {\n  FarmSchema,\n  FarmSchemaConstraint,\n  FarmSchemaField,\n  FarmSchemaFieldType,\n  FarmSchemaModel,\n  FarmSchemaModelExtension,\n  FarmSchemaModelOverride,\n  FarmSchemaReference,\n} from \"./schema\";\n\n// Keep the schema types available from the integrations entrypoint as well.\n// Integration declarations reference these types, and exporting them here\n// keeps those declarations nameable for consumers that import integration\n// helpers directly.\nexport type {\n  FarmSchema,\n  FarmSchemaConstraint,\n  FarmSchemaField,\n  FarmSchemaFieldType,\n  FarmSchemaModel,\n  FarmSchemaModelExtension,\n  FarmSchemaModelOverride,\n  FarmSchemaReference,\n} from \"./schema\";\n\n// Origin validation for integration auth routes is part of the integration\n// contract, so it is re-exported here alongside defineIntegration rather than\n// only from the package root.\nexport {\n  describeIntegrationOriginRejection,\n  resolveIntegrationAllowedOrigins,\n  validateIntegrationRequestOrigin,\n  type IntegrationOriginPolicy,\n  type IntegrationOriginRejection,\n  type IntegrationOriginResult,\n} from \"./integration-request-security\";\n\nimport type { ComponentType, ReactNode } from \"react\";\nimport { api as integrationApi, defineIntegrationAPIOperation } from \"./integration-api\";\nimport type {\n  FarmIntegrationAPI,\n  FarmIntegrationAPIBodyFormat,\n  FarmIntegrationAPIMethod,\n  FarmIntegrationAPIOperation,\n  FarmIntegrationAPIResponseFormat,\n  FarmIntegrationRouteOperationCarrier,\n  InferIntegrationAPIFromRoutes,\n} from \"./integration-api\";\nimport type { InferFarmIntegrationOrmClient } from \"./integration-orm\";\nimport { setFarmPluginIntegrationContext } from \"./plugin-integration-context\";\nimport { decodeRouteSegment } from \"./utils/decode\";\nimport {\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n  compareRouteSpecificity,\n  getRoutePatternSpecificity,\n} from \"./routing/specificity\";\nimport type {\n  FarmPlugin,\n  FarmPluginContext,\n  FarmPluginIntegrationContext,\n  FarmRequestStore,\n} from \"./plugin\";\nimport {\n  clearRequestContext,\n  deleteRequestContext,\n  getRequestContext,\n  getRequestContextSnapshot,\n  hasRequestContext,\n  setRequestContext,\n} from \"./request-context\";\nimport { applyWebResponseHeaders, sendWebResponse } from \"./server/response\";\nimport type { FarmRequest } from \"./types\";\nimport {\n  bufferFarmRequestBody,\n  createFarmRequestBodyErrorResponse,\n  readNodeRequestBody,\n  resolveFarmServerConfig,\n} from \"./server-http\";\n\nexport { api, defineIntegrationAPI, defineIntegrationAPIOperation } from \"./integration-api\";\nexport type {\n  FarmIntegrationAPI,\n  FarmIntegrationAPIBodyFormat,\n  FarmIntegrationAPIMethod,\n  FarmIntegrationAPIOperation,\n  FarmIntegrationAPIResponseFormat,\n} from \"./integration-api\";\n\nexport type FarmIntegrationCategory = \"auth\" | \"payment\" | \"monitoring\" | \"logging\" | (string & {});\n\n/** @deprecated Use FarmIntegrationCategory instead. */\nexport type FarmIntegrationSlot = FarmIntegrationCategory;\n\nexport type FarmIntegrationRouteParamValue = string | string[];\nexport type FarmIntegrationRouteParams = Record<string, FarmIntegrationRouteParamValue>;\nexport type FarmIntegrationRouteMethod =\n  | FarmIntegrationAPIMethod\n  | Lowercase<FarmIntegrationAPIMethod>\n  | \"ALL\"\n  | \"all\";\nexport type FarmIntegrationRouteInputSource = \"body\" | \"query\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type FarmIntegrationValidationPathSegment =\n  | PropertyKey\n  | {\n      readonly key: PropertyKey;\n    };\n\nexport interface FarmIntegrationRouteInput<TBody = unknown, TQuery = unknown> {\n  body?: TBody;\n  query?: TQuery;\n}\n\nexport interface FarmIntegrationValidationIssue {\n  source: FarmIntegrationRouteInputSource;\n  path?: readonly (string | number)[];\n  code?: string;\n  message: string;\n}\n\nexport interface FarmIntegrationValidationErrorLike {\n  issues?: readonly {\n    path?: readonly FarmIntegrationValidationPathSegment[];\n    code?: string;\n    message?: string;\n  }[];\n  message?: string;\n}\n\nexport type FarmIntegrationValidationResult<TValue> =\n  | {\n      success: true;\n      data: TValue;\n    }\n  | {\n      success: false;\n      error: FarmIntegrationValidationErrorLike;\n    };\n\nexport type FarmIntegrationStandardValidationResult<TValue> =\n  | {\n      value: TValue;\n    }\n  | {\n      issues: readonly {\n        path?: readonly FarmIntegrationValidationPathSegment[];\n        code?: string;\n        message: string;\n      }[];\n    };\n\nexport interface FarmIntegrationInputSchema<TValue = unknown> {\n  _output?: TValue;\n  parse?(value: unknown): MaybePromise<TValue>;\n  safeParse?(value: unknown): MaybePromise<FarmIntegrationValidationResult<TValue>>;\n  safeParseAsync?(value: unknown): Promise<FarmIntegrationValidationResult<TValue>>;\n  \"~standard\"?: {\n    validate(value: unknown): MaybePromise<FarmIntegrationStandardValidationResult<TValue>>;\n    types?: {\n      output: TValue;\n    };\n  };\n}\n\nexport interface FarmIntegrationRouteInputSchemas<TBody = unknown, TQuery = unknown> {\n  body?: FarmIntegrationInputSchema<TBody>;\n  query?: FarmIntegrationInputSchema<TQuery>;\n}\n\n/** @deprecated Use `FarmRequestStore` and access it through `ctx.req`. */\nexport type FarmIntegrationRequestContextStore = FarmRequestStore;\n\nexport const FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY = \"farm.integration.internalDispatch\";\n\n/**\n * Request-context key under which an integration middleware can hand\n * `Set-Cookie` values to the runtime when it returns `void` (i.e. lets the\n * request continue to the downstream route/page handler). The runtime reads\n * this key back after a `void` middleware return and forwards the cookies onto\n * the response it ultimately sends, so a server-side session refresh (or any\n * other cookie rotation) reaches the browser instead of being dropped.\n */\nexport const FARM_INTEGRATION_SET_COOKIES_KEY = \"farm:integration:set-cookies\";\n\n/**\n * Forward `Set-Cookie` values from an integration middleware that returns\n * `void` (the authenticated/passthrough branch) to the runtime, so they are\n * merged onto the response the runtime sends for the matched route. This is\n * the passthrough counterpart to appending `Set-Cookie` to a `Response` the\n * middleware returns directly (e.g. a failure redirect): both paths can rotate\n * auth cookies, and both must be able to reach the browser.\n */\nexport function forwardIntegrationSetCookies(\n  context: Pick<FarmIntegrationHandlerContext, \"req\">,\n  cookies: string[],\n): void {\n  if (cookies.length === 0) return;\n  const existing = context.req.get<string[]>(FARM_INTEGRATION_SET_COOKIES_KEY) ?? [];\n  context.req.set(FARM_INTEGRATION_SET_COOKIES_KEY, [...existing, ...cookies]);\n}\n\n/**\n * Read and clear the forwarded `Set-Cookie` values an integration middleware\n * stashed on the request context. Reading-and-clearing guarantees each batch\n * is applied at most once even when several middleware run for one request.\n */\nfunction takeForwardedIntegrationSetCookies(\n  context: Pick<FarmIntegrationHandlerContext, \"req\">,\n): string[] {\n  const cookies = context.req.get<string[]>(FARM_INTEGRATION_SET_COOKIES_KEY);\n  if (cookies && cookies.length > 0) {\n    context.req.delete(FARM_INTEGRATION_SET_COOKIES_KEY);\n    return cookies;\n  }\n  if (cookies) {\n    context.req.delete(FARM_INTEGRATION_SET_COOKIES_KEY);\n  }\n  return [];\n}\n\n/**\n * Return a copy of `response` carrying the forwarded `Set-Cookie` values, or\n * `response` unchanged when there is nothing to forward. Existing `Set-Cookie`\n * headers on the response are preserved (appended to, not replaced).\n */\nfunction appendIntegrationForwardedCookies(response: Response, cookies: string[]): Response {\n  if (cookies.length === 0) return response;\n  const headers = new Headers(response.headers);\n  for (const cookie of cookies) {\n    headers.append(\"set-cookie\", cookie);\n  }\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport type FarmIntegrationRouteDb<TSchema extends FarmIntegrationSchema | undefined> =\n  InferFarmIntegrationOrmClient<TSchema>;\n\nexport interface FarmIntegrationRouteStorageArgs<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  getClient(): Promise<unknown | undefined>;\n  getOrm(): Promise<FarmIntegrationRouteDb<TSchema>>;\n}\n\nexport interface FarmIntegrationRouteArgs<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  db: FarmIntegrationRouteDb<TSchema>;\n  getDb(): Promise<FarmIntegrationRouteDb<TSchema>>;\n  storage: FarmIntegrationRouteStorageArgs<TSchema>;\n}\n\nexport interface FarmIntegrationConfigContext<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  key: string;\n  integration: FarmIntegration<TSchema, any>;\n  appConfig: FarmPluginContext[\"config\"];\n  /** Alias for appConfig. */\n  config: FarmPluginContext[\"config\"];\n  args: FarmIntegrationRouteArgs<TSchema>;\n  env: Record<string, string | undefined>;\n  isDev: boolean;\n  isProd: boolean;\n}\n\nexport interface FarmIntegrationConfigDefinition<\n  TConfig = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  schema?: FarmIntegrationInputSchema<TConfig>;\n  env?: Record<string, string | readonly string[]>;\n  defaults?:\n    | Partial<TConfig>\n    | ((context: FarmIntegrationConfigContext<TSchema>) => MaybePromise<Partial<TConfig>>);\n  input?:\n    | Partial<TConfig>\n    | ((context: FarmIntegrationConfigContext<TSchema>) => MaybePromise<Partial<TConfig>>);\n  resolve?(\n    context: FarmIntegrationConfigContext<TSchema>,\n  ): MaybePromise<TConfig | Partial<TConfig> | undefined>;\n}\n\nexport type FarmIntegrationConfigInput<\n  TConfig = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = FarmIntegrationInputSchema<TConfig> | FarmIntegrationConfigDefinition<TConfig, TSchema>;\n\nexport type FarmIntegrationLifecycleLogLevel = \"info\" | \"warn\" | \"error\";\n\nexport interface FarmIntegrationLifecycleLogger {\n  info(message: string, meta?: Record<string, unknown>): void;\n  warn(message: string, meta?: Record<string, unknown>): void;\n  error(message: string, meta?: Record<string, unknown>): void;\n}\n\nexport interface FarmIntegrationLifecycleContext<\n  TConfig = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationConfigContext<TSchema> {\n  integration: FarmIntegration<TSchema, TConfig>;\n  integrationConfig: TConfig;\n  log: FarmIntegrationLifecycleLogger;\n  reason?: string;\n  cleanup(callback?: () => MaybePromise<void>): Promise<void>;\n}\n\nexport type FarmIntegrationLifecycleHook<\n  TConfig = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (context: FarmIntegrationLifecycleContext<TConfig, TSchema>) => MaybePromise<void>;\n\n/**\n * Small per-call integration metadata. Values received over HTTP are\n * client-controlled and should be validated before authorization decisions.\n */\nexport type FarmIntegrationData = Record<string, unknown>;\n\nexport interface FarmIntegrationHandlerContext<\n  TBody = unknown,\n  TQuery = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  request: Request;\n  requestId: string;\n  url: URL;\n  pathname: string;\n  method: string;\n  params: FarmIntegrationRouteParams;\n  input: FarmIntegrationRouteInput<TBody, TQuery>;\n  args: FarmIntegrationRouteArgs<TSchema>;\n  data: FarmIntegrationData;\n  integration: {\n    category: FarmIntegrationCategory;\n    /** @deprecated Use category instead. */\n    slot: FarmIntegrationCategory;\n    type: string;\n    instance: unknown;\n  };\n  route: {\n    kind: \"route\" | \"middleware\";\n    path: string;\n    methods: readonly string[];\n  };\n  req: FarmRequestStore;\n  /** @deprecated Use `req` instead. */\n  requestContext: FarmRequestStore;\n  config: FarmPluginContext[\"config\"];\n  isDev: boolean;\n  isProd: boolean;\n}\n\nexport interface FarmIntegrationRouteHookContext<\n  TBody = unknown,\n  TQuery = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationHandlerContext<TBody, TQuery, TSchema> {\n  response?: Response;\n}\n\nexport type FarmIntegrationRouteHook<\n  TBody = unknown,\n  TQuery = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = {\n  bivarianceHack(\n    request: Request,\n    context: FarmIntegrationRouteHookContext<TBody, TQuery, TSchema>,\n  ): Promise<Response | void> | Response | void;\n}[\"bivarianceHack\"];\n\nexport interface FarmIntegrationRoute<\n  TBody = unknown,\n  TQuery = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  path: string;\n  method?: FarmIntegrationRouteMethod;\n  methods?: readonly FarmIntegrationRouteMethod[];\n  middleware?: readonly FarmIntegrationRouteMiddleware<TSchema>[];\n  before?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n  after?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n  rawBody?: boolean;\n  bodyFormat?: FarmIntegrationAPIBodyFormat;\n  body?: FarmIntegrationInputSchema<TBody>;\n  query?: FarmIntegrationInputSchema<TQuery>;\n  input?: FarmIntegrationRouteInputSchemas<TBody, TQuery>;\n  handler(\n    request: Request,\n    context: FarmIntegrationHandlerContext<TBody, TQuery, TSchema>,\n  ): Promise<Response> | Response;\n}\n\nexport interface FarmTypedIntegrationRoute<\n  TPath extends string = string,\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationRoute<TBody, TQuery, TSchema> {\n  path: TPath;\n  method: TMethod;\n  __operation: FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>;\n}\n\nexport interface FarmIntegrationRouteMiddleware<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  handler(\n    request: Request,\n    context: FarmIntegrationHandlerContext<unknown, unknown, TSchema>,\n  ): Promise<Response | void> | Response | void;\n}\n\nexport interface FarmIntegrationMiddleware<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  matcher?: string | string[];\n  handler(\n    request: Request,\n    context: FarmIntegrationHandlerContext<unknown, unknown, TSchema>,\n  ): Promise<Response | void> | Response | void;\n}\n\nexport interface FarmIntegrationProviderProps {\n  children: ReactNode;\n}\n\nexport interface FarmIntegrationProviderComponentReference {\n  /** Client-safe module specifier using `@/`, a path relative to the app root, or a package. */\n  module: string;\n  /** Named export to use. Defaults to the module's default export. */\n  export?: string;\n}\n\nexport interface FarmIntegrationProvider {\n  name: string;\n  type: string;\n  props?: Record<string, unknown>;\n  /**\n   * The provider can be instantiated independently around each isolated\n   * client root without relying on context or state owned by the route root.\n   * Providers are treated as route-wide unless they explicitly opt in.\n   */\n  supportsIsolatedHydration?: boolean;\n  component?:\n    | ComponentType<FarmIntegrationProviderProps>\n    | FarmIntegrationProviderComponentReference;\n}\n\nexport interface FarmIntegrationDocumentNavigation {\n  matcher: string | readonly string[];\n}\n\n// The data schema is renderer- and feature-neutral: it now lives in ./schema\n// so applications can declare one without reaching into the integration API.\n// These aliases keep every shipped `*IntegrationSchema*` name working.\n\n/** @deprecated Use `FarmSchemaFieldType`. */\nexport type FarmIntegrationSchemaFieldType = FarmSchemaFieldType;\n\n/** @deprecated Use `FarmSchemaReference`. */\nexport type FarmIntegrationSchemaReference = FarmSchemaReference;\n\n/** @deprecated Use `FarmSchemaField`. */\nexport type FarmIntegrationSchemaField = FarmSchemaField;\n\n/** @deprecated Use `FarmSchemaConstraint`. */\nexport type FarmIntegrationSchemaConstraint = FarmSchemaConstraint;\n\n/** @deprecated Use `FarmSchemaModel`. */\nexport type FarmIntegrationSchemaModel = FarmSchemaModel;\n\n/** @deprecated Use `FarmSchemaModelExtension`. */\nexport type FarmIntegrationSchemaModelExtension = FarmSchemaModelExtension;\n\n/** @deprecated Use `FarmSchemaModelOverride`. */\nexport type FarmIntegrationSchemaModelOverride = FarmSchemaModelOverride;\n\n/** @deprecated Use `FarmSchema`. */\nexport type FarmIntegrationSchema = FarmSchema;\n\n/** @deprecated Use `defineSchema`. This is an exact alias, not a wrapper. */\nexport const defineIntegrationSchema = defineSchema;\n\nexport type FarmIntegrationLogPhase =\n  | \"registered\"\n  | \"validate\"\n  | \"setup\"\n  | \"ready\"\n  | \"dispose\"\n  | \"request:start\"\n  | \"request:end\"\n  | \"request:error\";\n\nexport interface FarmIntegrationLogEvent {\n  category: FarmIntegrationCategory;\n  /** @deprecated Use category instead. */\n  slot: FarmIntegrationCategory;\n  type: string;\n  phase: FarmIntegrationLogPhase;\n  route?: {\n    kind: \"route\" | \"middleware\";\n    path: string;\n    methods: readonly string[];\n  };\n  requestId?: string;\n  request?: Request;\n  response?: Response;\n  error?: unknown;\n  durationMs?: number;\n  level?: FarmIntegrationLifecycleLogLevel;\n  message?: string;\n  meta?: Record<string, unknown>;\n  context: Map<string, unknown>;\n}\n\nexport type FarmIntegrationLogger = (event: FarmIntegrationLogEvent) => void | Promise<void>;\n\nexport interface FarmIntegrationPluginOwner {\n  key: string;\n  category: FarmIntegrationCategory;\n  type: string;\n  source: \"lifecycle\" | \"contribution\";\n  serverRuntime: boolean;\n}\n\n/** A normal plugin or an integration-bound plugin compatible with the shared instance. */\nexport type FarmIntegrationContributedPlugin<TInstance = unknown> =\n  | FarmPlugin<any, any, any, any, unknown, false>\n  | FarmPlugin<any, any, any, any, TInstance, true>;\n\nexport interface FarmIntegration<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n  TConfig = unknown,\n  TInstance = unknown,\n> {\n  readonly kind: \"farm-integration\";\n  category: FarmIntegrationCategory;\n  /** @deprecated Use category instead. */\n  slot?: FarmIntegrationCategory;\n  type: string;\n  instance: TInstance;\n  /** Set to false when a platform adapter owns this integration's production routes. */\n  serverRuntime?: boolean;\n  api?: FarmIntegrationAPI;\n  schema?: TSchema;\n  config?: FarmIntegrationConfigInput<TConfig, TSchema>;\n  validate?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n  setup?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n  ready?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n  dispose?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n  log?: FarmIntegrationLogger;\n  routes?: readonly FarmIntegrationRoute<any, any, TSchema>[];\n  endpoints?: FarmIntegrationEndpoints<TSchema>;\n  middleware?: readonly FarmIntegrationMiddleware<TSchema>[];\n  providers?: readonly FarmIntegrationProvider[];\n  documentNavigations?: readonly FarmIntegrationDocumentNavigation[];\n  /** Additional Farm plugins owned and configured by this integration. */\n  plugins?: readonly FarmIntegrationContributedPlugin<NoInfer<TInstance>>[];\n}\n\nexport type FarmIntegrationsUserConfig = Record<string, FarmIntegration<any, any, any> | undefined>;\n\nconst FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME = Symbol.for(\n  \"@farm.js/core/integration-plugin-server-runtime\",\n);\nconst FARM_INTEGRATION_PLUGIN_OWNER = Symbol.for(\"@farm.js/core/integration-plugin-owner\");\n\n/** @internal Identifies plugins owned by platform-managed integrations. */\nexport function getFarmIntegrationPluginServerRuntime(plugin: FarmPlugin): boolean | undefined {\n  const value = (plugin as FarmPlugin & Record<symbol, unknown>)[\n    FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME\n  ];\n  return typeof value === \"boolean\" ? value : undefined;\n}\n\n/** Returns the integration that contributed a normalized plugin, when applicable. */\nexport function getFarmIntegrationPluginOwner(\n  plugin: FarmPlugin,\n): Readonly<FarmIntegrationPluginOwner> | undefined {\n  const value = (plugin as FarmPlugin & Record<symbol, unknown>)[FARM_INTEGRATION_PLUGIN_OWNER];\n  return value && typeof value === \"object\"\n    ? (value as Readonly<FarmIntegrationPluginOwner>)\n    : undefined;\n}\n\ntype IntegrationRouteBuilderOptions<\n  TBody,\n  TQuery,\n  TServer extends boolean,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = {\n  middleware?: readonly FarmIntegrationRouteMiddleware<TSchema>[];\n  before?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n  after?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n  rawBody?: boolean;\n  headers?: Record<string, string>;\n  credentials?: RequestCredentials;\n  bodyFormat?: FarmIntegrationAPIBodyFormat;\n  responseFormat?: FarmIntegrationAPIResponseFormat;\n  isServer?: TServer;\n  body?: FarmIntegrationInputSchema<TBody>;\n  query?: FarmIntegrationInputSchema<TQuery>;\n  input?: FarmIntegrationRouteInputSchemas<TBody, TQuery>;\n  handler(\n    request: Request,\n    context: FarmIntegrationHandlerContext<TBody, TQuery, TSchema>,\n  ): Promise<Response> | Response;\n};\n\nfunction defineTypedIntegrationRoute<\n  TPath extends string,\n  TBody,\n  TQuery,\n  TResponse,\n  TServer extends boolean,\n  TMethod extends FarmIntegrationAPIMethod,\n  TSchema extends FarmIntegrationSchema | undefined,\n>(\n  method: TMethod,\n  path: TPath,\n  input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, TMethod, TSchema> {\n  return {\n    path,\n    method,\n    middleware: input.middleware,\n    before: input.before,\n    after: input.after,\n    rawBody: input.rawBody,\n    bodyFormat: input.bodyFormat,\n    input: normalizeIntegrationRouteInputSchemas(input),\n    handler: input.handler,\n    __operation: defineIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>({\n      path,\n      method,\n      bodyFormat: input.bodyFormat,\n      responseFormat: input.responseFormat,\n      headers: input.headers,\n      credentials: input.credentials,\n      isServer: input.isServer,\n    }),\n  };\n}\n\nexport interface FarmIntegrationRouteFactory<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  get<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    path: TPath,\n    input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n  ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"GET\", TSchema>;\n  post<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"POST\", TSchema>;\n  query<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"QUERY\", TSchema>;\n  put<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PUT\", TSchema>;\n  patch<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PATCH\", TSchema>;\n  delete<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"DELETE\", TSchema>;\n  options<\n    TPath extends string,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n  ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"OPTIONS\", TSchema>;\n  head<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    path: TPath,\n    input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n  ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"HEAD\", TSchema>;\n}\n\nexport interface FarmIntegrationRoutesFactoryContext<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  route: FarmIntegrationRouteFactory<TSchema>;\n  integrationRoute: FarmIntegrationRouteFactory<TSchema>;\n}\n\nexport type FarmIntegrationRoutesFactory<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (\n  context: FarmIntegrationRoutesFactoryContext<TSchema>,\n) => readonly FarmIntegrationRoute<any, any, TSchema>[];\n\nexport type FarmIntegrationEndpointValue<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> =\n  | FarmIntegrationRoute<any, any, TSchema>\n  | readonly FarmIntegrationEndpointValue<TSchema>[]\n  | {\n      readonly [key: string]: FarmIntegrationEndpointValue<TSchema> | undefined;\n    };\n\nexport type FarmIntegrationEndpoints<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = {\n  readonly [key: string]: FarmIntegrationEndpointValue<TSchema> | undefined;\n};\n\nexport interface FarmIntegrationEndpointsFactoryContext<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationRoutesFactoryContext<TSchema> {\n  endpoint: FarmIntegrationRouteFactory<TSchema>;\n}\n\nexport type FarmIntegrationEndpointsFactory<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (context: FarmIntegrationEndpointsFactoryContext<TSchema>) => FarmIntegrationEndpoints<TSchema>;\n\nfunction createIntegrationRouteFactory<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n>(): FarmIntegrationRouteFactory<TSchema> {\n  return {\n    get<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      path: TPath,\n      input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n    ) {\n      return defineTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"GET\", TSchema>(\n        \"GET\",\n        path,\n        input,\n      );\n    },\n    post<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"POST\", TSchema>(\n        \"POST\",\n        path,\n        {\n          bodyFormat: \"json\",\n          ...input,\n        },\n      );\n    },\n    query<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<\n        TPath,\n        TBody,\n        TQuery,\n        TResponse,\n        TServer,\n        \"QUERY\",\n        TSchema\n      >(\"QUERY\", path, {\n        bodyFormat: \"json\",\n        ...input,\n      });\n    },\n    put<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PUT\", TSchema>(\n        \"PUT\",\n        path,\n        {\n          bodyFormat: \"json\",\n          ...input,\n        },\n      );\n    },\n    patch<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<\n        TPath,\n        TBody,\n        TQuery,\n        TResponse,\n        TServer,\n        \"PATCH\",\n        TSchema\n      >(\"PATCH\", path, {\n        bodyFormat: \"json\",\n        ...input,\n      });\n    },\n    delete<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<\n        TPath,\n        TBody,\n        TQuery,\n        TResponse,\n        TServer,\n        \"DELETE\",\n        TSchema\n      >(\"DELETE\", path, {\n        bodyFormat: \"json\",\n        ...input,\n      });\n    },\n    options<\n      TPath extends string,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(\n      path: TPath,\n      input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n    ) {\n      return defineTypedIntegrationRoute<\n        TPath,\n        never,\n        TQuery,\n        TResponse,\n        TServer,\n        \"OPTIONS\",\n        TSchema\n      >(\"OPTIONS\", path, input);\n    },\n    head<\n      TPath extends string,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(\n      path: TPath,\n      input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n    ) {\n      return defineTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"HEAD\", TSchema>(\n        \"HEAD\",\n        path,\n        input,\n      );\n    },\n  };\n}\n\nexport function createIntegrationRoute<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n>(_schema?: TSchema): FarmIntegrationRouteFactory<TSchema> {\n  return createIntegrationRouteFactory<TSchema>();\n}\n\nexport const integrationRoute = createIntegrationRouteFactory<undefined>();\n\ntype RegisteredIntegrationRuntime = {\n  integration: FarmIntegration;\n  config: FarmPluginContext[\"config\"];\n  isDev: boolean;\n  isProd: boolean;\n};\n\nconst INTEGRATION_RUNTIME_REGISTRY_KEY = Symbol.for(\"farm.integrationRuntimeRegistry\");\nconst INTEGRATION_REQUEST_DISPATCHER_KEY = Symbol.for(\"farm.integrationRequestDispatcher\");\n\ntype IntegrationRequestDispatcher = (\n  runtime: RegisteredIntegrationRuntime,\n  request: Request,\n  options?: { currentRequest?: Request },\n) => Promise<Response | null>;\n\ntype GlobalWithIntegrationRuntimeRegistry = typeof globalThis & {\n  [INTEGRATION_RUNTIME_REGISTRY_KEY]?: Map<string, RegisteredIntegrationRuntime>;\n  [INTEGRATION_REQUEST_DISPATCHER_KEY]?: IntegrationRequestDispatcher;\n};\n\nfunction getIntegrationRuntimeRegistry() {\n  const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n  if (!globalState[INTEGRATION_RUNTIME_REGISTRY_KEY]) {\n    globalState[INTEGRATION_RUNTIME_REGISTRY_KEY] = new Map<string, RegisteredIntegrationRuntime>();\n  }\n\n  return globalState[INTEGRATION_RUNTIME_REGISTRY_KEY]!;\n}\n\ntype FarmIntegrationRoutesInput<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = readonly FarmIntegrationRoute<any, any, TSchema>[] | FarmIntegrationRoutesFactory<TSchema>;\n\ntype FarmIntegrationEndpointsInput<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = FarmIntegrationEndpoints<TSchema> | FarmIntegrationEndpointsFactory<TSchema>;\n\ntype FarmIntegrationInput<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n  TConfig = unknown,\n  TInstance = unknown,\n> = Omit<\n  FarmIntegration<TSchema, TConfig, TInstance>,\n  \"kind\" | \"category\" | \"slot\" | \"instance\" | \"config\" | \"routes\" | \"endpoints\" | \"plugins\"\n> & {\n  instance: TInstance;\n  config?: FarmIntegrationConfigInput<TConfig, TSchema>;\n  routes?: FarmIntegrationRoutesInput<TSchema>;\n  endpoints?: FarmIntegrationEndpointsInput<TSchema>;\n  plugins?: readonly FarmIntegrationContributedPlugin<NoInfer<TInstance>>[];\n} & (\n    | {\n        category: FarmIntegrationCategory;\n        slot?: FarmIntegrationCategory;\n      }\n    | {\n        category?: FarmIntegrationCategory;\n        slot: FarmIntegrationCategory;\n      }\n  );\n\ntype FarmIntegrationCategoryInput =\n  | {\n      category: FarmIntegrationCategory;\n      slot?: FarmIntegrationCategory;\n    }\n  | {\n      category?: FarmIntegrationCategory;\n      slot: FarmIntegrationCategory;\n    };\n\ntype FarmIntegrationShapeForInference = FarmIntegrationCategoryInput & {\n  api?: FarmIntegrationAPI;\n  schema?: FarmIntegrationSchema;\n  config?: unknown;\n  routes?: unknown;\n  endpoints?: unknown;\n};\n\ntype ExtractIntegrationSchema<TIntegration> = TIntegration extends {\n  schema: infer TSchema extends FarmIntegrationSchema;\n}\n  ? TSchema\n  : undefined;\n\ntype ResolveIntegrationRoutesInput<TRoutes, TSchema extends FarmIntegrationSchema | undefined> =\n  TRoutes extends FarmIntegrationRoutesFactory<TSchema> ? ReturnType<TRoutes> : TRoutes;\n\ntype ResolveIntegrationEndpointsInput<\n  TEndpoints,\n  TSchema extends FarmIntegrationSchema | undefined,\n> =\n  TEndpoints extends FarmIntegrationEndpointsFactory<TSchema> ? ReturnType<TEndpoints> : TEndpoints;\n\ntype ExtractIntegrationRoutesFromRoutesInput<\n  TRoutes,\n  TSchema extends FarmIntegrationSchema | undefined,\n> =\n  ResolveIntegrationRoutesInput<TRoutes, TSchema> extends readonly (infer TRoute)[]\n    ? TRoute\n    : never;\n\ntype ExtractIntegrationRoutesFromEndpointValue<TValue> =\n  TValue extends FarmIntegrationRouteOperationCarrier<string, any>\n    ? TValue\n    : TValue extends readonly (infer TItem)[]\n      ? ExtractIntegrationRoutesFromEndpointValue<TItem>\n      : TValue extends object\n        ? ExtractIntegrationRoutesFromEndpointValue<TValue[keyof TValue]>\n        : never;\n\ntype ExtractIntegrationRoutesFromEndpointsInput<\n  TEndpoints,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = ExtractIntegrationRoutesFromEndpointValue<\n  ResolveIntegrationEndpointsInput<TEndpoints, TSchema>\n>;\n\ntype ExtractIntegrationRouteUnion<TIntegration, TSchema extends FarmIntegrationSchema | undefined> =\n  | (TIntegration extends { routes: infer TRoutes }\n      ? ExtractIntegrationRoutesFromRoutesInput<TRoutes, TSchema>\n      : never)\n  | (TIntegration extends { endpoints: infer TEndpoints }\n      ? ExtractIntegrationRoutesFromEndpointsInput<TEndpoints, TSchema>\n      : never);\n\ntype ExtractDefinedIntegrationRoutes<\n  TIntegration,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = [ExtractIntegrationRouteUnion<TIntegration, TSchema>] extends [never]\n  ? undefined\n  : readonly ExtractIntegrationRouteUnion<TIntegration, TSchema>[];\n\ntype ExtractDefinedIntegrationEndpoints<\n  TIntegration,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = TIntegration extends { endpoints: infer TEndpoints }\n  ? ResolveIntegrationEndpointsInput<TEndpoints, TSchema>\n  : undefined;\n\ntype ExtractIntegrationAPIRoutes<\n  TIntegration,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = Extract<\n  ExtractIntegrationRouteUnion<TIntegration, TSchema>,\n  FarmIntegrationRouteOperationCarrier<string, any>\n>;\n\ntype ExtractIntegrationCategory<TIntegration extends FarmIntegrationCategoryInput> =\n  TIntegration extends {\n    category: infer TCategory extends FarmIntegrationCategory;\n  }\n    ? TCategory\n    : TIntegration extends { slot: infer TSlot extends FarmIntegrationCategory }\n      ? TSlot\n      : FarmIntegrationCategory;\n\ntype ExtractDerivedIntegrationAPI<\n  TIntegration extends FarmIntegrationShapeForInference,\n  TSchema extends FarmIntegrationSchema | undefined = ExtractIntegrationSchema<TIntegration>,\n> = TIntegration extends { api: infer TAPI extends FarmIntegrationAPI }\n  ? TAPI\n  : [ExtractIntegrationAPIRoutes<TIntegration, TSchema>] extends [never]\n    ? FarmIntegrationAPI | undefined\n    : InferIntegrationAPIFromRoutes<readonly ExtractIntegrationAPIRoutes<TIntegration, TSchema>[]>;\n\nexport type DefinedIntegration<\n  TIntegration extends FarmIntegrationShapeForInference,\n  TSchema extends FarmIntegrationSchema | undefined = ExtractIntegrationSchema<TIntegration>,\n> = Omit<TIntegration, \"kind\" | \"category\" | \"slot\" | \"api\" | \"routes\" | \"endpoints\"> & {\n  readonly kind: \"farm-integration\";\n  category: ExtractIntegrationCategory<TIntegration>;\n  slot: ExtractIntegrationCategory<TIntegration>;\n  routes: ExtractDefinedIntegrationRoutes<TIntegration, TSchema>;\n  endpoints: ExtractDefinedIntegrationEndpoints<TIntegration, TSchema>;\n  api: ExtractDerivedIntegrationAPI<TIntegration, TSchema>;\n};\n\nfunction isIntegrationEndpointRoute(value: unknown): value is FarmIntegrationRoute {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as { path?: unknown }).path === \"string\" &&\n    typeof (value as { handler?: unknown }).handler === \"function\"\n  );\n}\n\nfunction flattenIntegrationEndpoints(\n  endpoints: FarmIntegrationEndpointValue | FarmIntegrationEndpoints | undefined,\n): FarmIntegrationRoute[] {\n  if (!endpoints) {\n    return [];\n  }\n\n  if (Array.isArray(endpoints)) {\n    return endpoints.flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));\n  }\n\n  if (isIntegrationEndpointRoute(endpoints)) {\n    return [endpoints];\n  }\n\n  if (typeof endpoints === \"object\") {\n    return Object.values(endpoints).flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));\n  }\n\n  return [];\n}\n\nexport function defineIntegration<\n  const TSchema extends FarmIntegrationSchema | undefined,\n  const TConfig,\n  TIntegration extends FarmIntegrationInput<TSchema, TConfig, any>,\n>(\n  integration: TIntegration &\n    FarmIntegrationInput<TSchema, TConfig, NoInfer<TIntegration[\"instance\"]>>,\n): DefinedIntegration<TIntegration, TSchema>;\nexport function defineIntegration<\n  const TSchema extends FarmIntegrationSchema | undefined,\n  const TConfig,\n  TIntegration extends FarmIntegrationInput<TSchema, TConfig, any>,\n>(\n  integration: TIntegration &\n    FarmIntegrationInput<TSchema, TConfig, NoInfer<TIntegration[\"instance\"]>>,\n): DefinedIntegration<TIntegration, TSchema> {\n  const category = integration.category ?? integration.slot;\n\n  if (!category) {\n    throw new Error(\"Integration category is required.\");\n  }\n\n  if (integration.category && integration.slot && integration.category !== integration.slot) {\n    throw new Error(\"Integration category and slot must match when both are provided.\");\n  }\n\n  const routeFactory = createIntegrationRoute(integration.schema);\n  const routes =\n    typeof integration.routes === \"function\"\n      ? integration.routes({\n          route: routeFactory,\n          integrationRoute: routeFactory,\n        })\n      : integration.routes;\n  const endpoints =\n    typeof integration.endpoints === \"function\"\n      ? integration.endpoints({\n          endpoint: routeFactory,\n          route: routeFactory,\n          integrationRoute: routeFactory,\n        })\n      : integration.endpoints;\n  const endpointRoutes = flattenIntegrationEndpoints(endpoints);\n  const allRoutes =\n    routes?.length || endpointRoutes.length\n      ? ([...(routes || []), ...endpointRoutes] as readonly FarmIntegrationRoute[])\n      : undefined;\n\n  for (const route of allRoutes || []) {\n    assertUniqueRouteParameters(route.path, \"api\");\n    validateConfigRouteSource(route.path, `Integration route \"${route.path}\"`);\n    assertTerminalCatchAll(route.path, \"api\");\n  }\n\n  const derivedApi =\n    integration.api ||\n    (allRoutes?.length\n      ? integrationApi.fromRoutes(\n          allRoutes as unknown as ReadonlyArray<{\n            path: string;\n            __operation: FarmIntegrationAPIOperation<any, any, any, any, any>;\n          }>,\n        )\n      : undefined);\n\n  return {\n    kind: \"farm-integration\",\n    ...integration,\n    endpoints,\n    routes: allRoutes,\n    api: derivedApi,\n    category,\n    slot: category,\n  } as unknown as DefinedIntegration<TIntegration, TSchema>;\n}\n\nexport function isFarmIntegration(value: unknown): value is FarmIntegration {\n  return (\n    !!value && typeof value === \"object\" && (value as FarmIntegration).kind === \"farm-integration\"\n  );\n}\n\nexport function resolveIntegrationPlugins(\n  integrations: FarmIntegrationsUserConfig | undefined,\n): FarmPlugin[] {\n  if (!integrations) {\n    return [];\n  }\n\n  const plugins: FarmPlugin[] = [];\n  for (const [key, integration] of Object.entries(integrations)) {\n    if (!integration || !isFarmIntegration(integration)) {\n      continue;\n    }\n\n    const owner = createIntegrationPluginOwner(key, integration, \"lifecycle\");\n    plugins.push(withIntegrationPluginOwner(createIntegrationPlugin(key, integration), owner));\n    plugins.push(...resolveIntegrationPluginContributions(key, integration));\n  }\n\n  return plugins;\n}\n\nfunction resolveIntegrationPluginContributions(\n  key: string,\n  integration: FarmIntegration<any, any>,\n): FarmPlugin[] {\n  const contributions = integration.plugins;\n  if (!contributions) return [];\n  if (!Array.isArray(contributions)) {\n    throw new TypeError(`Integration \"${key}\" plugins must be an array`);\n  }\n\n  const names = new Set<string>();\n  return contributions.map((plugin, index) => {\n    if (!plugin || typeof plugin !== \"object\" || typeof plugin.name !== \"string\") {\n      throw new TypeError(`Integration \"${key}\" plugin at index ${index} is invalid`);\n    }\n    const name = plugin.name.trim();\n    if (!name) {\n      throw new TypeError(`Integration \"${key}\" plugin at index ${index} requires a name`);\n    }\n    if (names.has(name)) {\n      throw new Error(`Integration \"${key}\" contributes duplicate plugin name \"${name}\"`);\n    }\n    names.add(name);\n\n    return withIntegrationPluginOwner(\n      plugin,\n      createIntegrationPluginOwner(key, integration, \"contribution\"),\n      createIntegrationPluginContext(key, integration),\n    );\n  });\n}\n\nfunction createIntegrationPluginOwner(\n  key: string,\n  integration: FarmIntegration<any, any>,\n  source: FarmIntegrationPluginOwner[\"source\"],\n): Readonly<FarmIntegrationPluginOwner> {\n  return Object.freeze({\n    key,\n    category: integration.category,\n    type: integration.type,\n    source,\n    serverRuntime: integration.serverRuntime !== false,\n  });\n}\n\nfunction createIntegrationPluginContext(\n  key: string,\n  integration: FarmIntegration<any, any>,\n): Readonly<FarmPluginIntegrationContext> {\n  return Object.freeze({\n    key,\n    category: integration.category,\n    type: integration.type,\n    instance: integration.instance,\n    serverRuntime: integration.serverRuntime !== false,\n  });\n}\n\nfunction withIntegrationPluginOwner(\n  plugin: FarmPlugin<any, any, any, any, any, boolean>,\n  owner: Readonly<FarmIntegrationPluginOwner>,\n  integration?: Readonly<FarmPluginIntegrationContext>,\n): FarmPlugin {\n  const descriptors = Object.getOwnPropertyDescriptors(plugin);\n  Reflect.deleteProperty(descriptors, FARM_INTEGRATION_PLUGIN_OWNER);\n  Reflect.deleteProperty(descriptors, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME);\n  const ownedPlugin = Object.create(Object.getPrototypeOf(plugin), descriptors) as FarmPlugin;\n  Object.defineProperty(ownedPlugin, FARM_INTEGRATION_PLUGIN_OWNER, { value: owner });\n  Object.defineProperty(ownedPlugin, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME, {\n    value: owner.serverRuntime,\n  });\n  if (integration) {\n    setFarmPluginIntegrationContext(ownedPlugin, integration);\n  }\n  return ownedPlugin;\n}\n\nexport function getIntegrationProviders(\n  integrations: FarmIntegrationsUserConfig | undefined,\n): FarmIntegrationProvider[] {\n  if (!integrations) {\n    return [];\n  }\n\n  const providers: FarmIntegrationProvider[] = [];\n  for (const integration of Object.values(integrations)) {\n    if (!integration || !isFarmIntegration(integration) || !integration.providers?.length) {\n      continue;\n    }\n\n    for (const provider of integration.providers) {\n      providers.push({\n        name: provider.name,\n        type: provider.type,\n        props: provider.props,\n        supportsIsolatedHydration: provider.supportsIsolatedHydration,\n        component: provider.component,\n      });\n    }\n  }\n\n  return providers;\n}\n\nexport function isFarmIntegrationProviderComponentReference(\n  value: FarmIntegrationProvider[\"component\"],\n): value is FarmIntegrationProviderComponentReference {\n  return Boolean(\n    value &&\n    typeof value === \"object\" &&\n    \"module\" in value &&\n    typeof value.module === \"string\" &&\n    value.module.length > 0,\n  );\n}\n\nexport function getIntegrationDocumentNavigationMatchers(\n  integrations: FarmIntegrationsUserConfig | undefined,\n): string[] {\n  if (!integrations) {\n    return [];\n  }\n\n  const matchers: string[] = [];\n  for (const integration of Object.values(integrations)) {\n    if (\n      !integration ||\n      !isFarmIntegration(integration) ||\n      !integration.documentNavigations?.length\n    ) {\n      continue;\n    }\n\n    for (const navigation of integration.documentNavigations) {\n      const items = Array.isArray(navigation.matcher) ? navigation.matcher : [navigation.matcher];\n\n      for (const item of items) {\n        matchers.push(item);\n      }\n    }\n  }\n\n  return matchers;\n}\n\nexport function getIntegrationSchemas(\n  integrations: FarmIntegrationsUserConfig | undefined,\n): Record<string, FarmIntegrationSchema> {\n  if (!integrations) {\n    return {};\n  }\n\n  const schemaEntries = Object.entries(integrations)\n    .map(([key, integration]) => {\n      const schema = integration && isFarmIntegration(integration) ? integration.schema : undefined;\n      return schema ? ([key, schema] as const) : null;\n    })\n    .filter((value): value is readonly [string, FarmIntegrationSchema] => value !== null);\n\n  return Object.fromEntries(schemaEntries);\n}\n\nexport function getRegisteredIntegrationRuntime(\n  key: string,\n): RegisteredIntegrationRuntime | undefined {\n  return getIntegrationRuntimeRegistry().get(key);\n}\n\nexport function getRegisteredIntegrations(): Record<string, FarmIntegration> {\n  return Object.fromEntries(\n    Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [\n      key,\n      runtime.integration,\n    ]),\n  );\n}\n\nexport function getRegisteredIntegrationSchemas(): Record<string, FarmIntegrationSchema> {\n  return getIntegrationSchemas(getRegisteredIntegrations());\n}\n\nexport function matchIntegrationRoute(\n  integrations: FarmIntegrationsUserConfig | undefined,\n  input: {\n    pathname: string;\n    method?: string;\n  },\n): {\n  key: string;\n  integration: FarmIntegration;\n  route: {\n    path: string;\n    methods: readonly string[];\n  };\n  params: FarmIntegrationRouteParams;\n} | null {\n  if (!integrations) {\n    return null;\n  }\n\n  for (const [key, integration] of Object.entries(integrations)) {\n    if (!integration || !isFarmIntegration(integration)) {\n      continue;\n    }\n\n    const routes = normalizeIntegrationRoutes(integration.routes || []);\n\n    for (const route of routes) {\n      if (!matchesMethod(route.methods, input.method)) {\n        continue;\n      }\n\n      const params = extractPathParams(route.path, input.pathname);\n      if (!params) {\n        continue;\n      }\n\n      return {\n        key,\n        integration,\n        route: {\n          path: route.path,\n          methods: route.methods,\n        },\n        params,\n      };\n    }\n  }\n\n  return null;\n}\n\nexport function matchRegisteredIntegrationRoute(input: { pathname: string; method?: string }): {\n  key: string;\n  integration: FarmIntegration;\n  route: {\n    path: string;\n    methods: readonly string[];\n  };\n  params: FarmIntegrationRouteParams;\n} | null {\n  return matchIntegrationRoute(getRegisteredIntegrations(), input);\n}\n\nfunction createClientSafeIntegrationAPI(\n  api: FarmIntegrationAPI | undefined,\n): FarmIntegrationAPI | undefined {\n  if (!api) {\n    return undefined;\n  }\n\n  const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n    if (\n      value &&\n      typeof value === \"object\" &&\n      (value as FarmIntegrationAPIOperation<any, any, any, any, any>).kind ===\n        \"farm-integration-api-operation\"\n    ) {\n      const operation = value as FarmIntegrationAPIOperation<any, any, any, any, any>;\n      return [\n        key,\n        defineIntegrationAPIOperation({\n          path: operation.path,\n          method: operation.method,\n          bodyFormat: operation.bodyFormat,\n          responseFormat: operation.responseFormat,\n          credentials: operation.credentials,\n          isServer: operation.isServer,\n        }),\n      ];\n    }\n\n    if (value && typeof value === \"object\") {\n      return [key, createClientSafeIntegrationAPI(value as FarmIntegrationAPI)];\n    }\n\n    return [key, value];\n  });\n\n  return Object.fromEntries(entries) as FarmIntegrationAPI;\n}\n\nexport function getRegisteredIntegrationAPIManifest(): Record<string, FarmIntegrationAPI> {\n  const manifestEntries = Object.entries(getRegisteredIntegrations())\n    .map(([key, integration]) => {\n      const api = createClientSafeIntegrationAPI(integration.api);\n      return api ? ([key, api] as const) : null;\n    })\n    .filter((value): value is readonly [string, FarmIntegrationAPI] => value !== null);\n\n  return Object.fromEntries(manifestEntries);\n}\n\ntype IntegrationLifecycleCleanup = () => MaybePromise<void>;\n\nfunction getIntegrationRuntimeEnv(): Record<string, string | undefined> {\n  return typeof process !== \"undefined\" ? process.env : {};\n}\n\nfunction isIntegrationConfigDefinition(\n  value: unknown,\n): value is FarmIntegrationConfigDefinition<unknown> {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (\"schema\" in value ||\n      \"env\" in value ||\n      \"defaults\" in value ||\n      \"input\" in value ||\n      \"resolve\" in value)\n  );\n}\n\nfunction mergeIntegrationConfigValue(current: unknown, next: unknown): unknown {\n  if (next === undefined) {\n    return current;\n  }\n\n  if (isPlainIntegrationConfigObject(current) && isPlainIntegrationConfigObject(next)) {\n    return {\n      ...current,\n      ...next,\n    };\n  }\n\n  return next;\n}\n\nfunction isPlainIntegrationConfigObject(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nasync function resolveIntegrationConfigPart<TValue>(\n  value: TValue | ((context: FarmIntegrationConfigContext) => MaybePromise<TValue>) | undefined,\n  context: FarmIntegrationConfigContext,\n): Promise<TValue | undefined> {\n  if (typeof value === \"function\") {\n    return (value as (context: FarmIntegrationConfigContext) => MaybePromise<TValue>)(context);\n  }\n\n  return value;\n}\n\nfunction resolveIntegrationEnvConfig(\n  env: Record<string, string | readonly string[]> | undefined,\n): Record<string, string> | undefined {\n  if (!env) {\n    return undefined;\n  }\n\n  const runtimeEnv = getIntegrationRuntimeEnv();\n  const config: Record<string, string> = {};\n\n  for (const [key, names] of Object.entries(env)) {\n    const envNames = Array.isArray(names) ? names : [names];\n    const value = envNames.map((name) => runtimeEnv[name]).find((entry) => entry !== undefined);\n    if (value !== undefined) {\n      config[key] = value;\n    }\n  }\n\n  return config;\n}\n\nasync function parseIntegrationConfigSchema<TConfig>(\n  integration: FarmIntegration<any, any>,\n  schema: FarmIntegrationInputSchema<TConfig>,\n  value: unknown,\n): Promise<TConfig> {\n  const parser = schema.safeParseAsync || schema.safeParse;\n  if (parser) {\n    const result = await parser.call(schema, value);\n    if (result.success) {\n      return result.data;\n    }\n\n    throw createIntegrationConfigValidationError(integration, result.error);\n  }\n\n  if (schema[\"~standard\"]?.validate) {\n    const result = await schema[\"~standard\"].validate(value);\n    if (\"value\" in result) {\n      return result.value;\n    }\n\n    throw createIntegrationConfigValidationError(integration, {\n      issues: result.issues,\n    });\n  }\n\n  if (schema.parse) {\n    try {\n      return await schema.parse(value);\n    } catch (error) {\n      throw createIntegrationConfigValidationError(\n        integration,\n        normalizeIntegrationValidationError(error),\n      );\n    }\n  }\n\n  throw new Error(\n    `Integration \"${integration.type}\" config schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.`,\n  );\n}\n\nfunction createIntegrationConfigValidationError(\n  integration: FarmIntegration<any, any>,\n  error: FarmIntegrationValidationErrorLike,\n) {\n  const issues =\n    Array.isArray(error.issues) && error.issues.length > 0\n      ? error.issues\n          .map((issue) => {\n            const normalizedPath = normalizeIntegrationValidationPath(issue.path);\n            const path = normalizedPath.length ? `${normalizedPath.join(\".\")}: ` : \"\";\n            return `${path}${issue.message || \"Invalid config\"}`;\n          })\n          .join(\"; \")\n      : error.message || \"Invalid config\";\n\n  return new Error(`Integration \"${integration.type}\" config validation failed: ${issues}`);\n}\n\nasync function resolveIntegrationConfig<TConfig>(\n  integration: FarmIntegration<any, TConfig>,\n  context: FarmIntegrationConfigContext,\n): Promise<TConfig> {\n  const config = integration.config;\n  if (!config) {\n    return undefined as TConfig;\n  }\n\n  if (!isIntegrationConfigDefinition(config)) {\n    return parseIntegrationConfigSchema(integration, config, {});\n  }\n\n  let value: unknown = {};\n  value = mergeIntegrationConfigValue(\n    value,\n    await resolveIntegrationConfigPart(config.defaults, context),\n  );\n  value = mergeIntegrationConfigValue(value, resolveIntegrationEnvConfig(config.env));\n  value = mergeIntegrationConfigValue(\n    value,\n    await resolveIntegrationConfigPart(config.input, context),\n  );\n  value = mergeIntegrationConfigValue(value, await config.resolve?.(context));\n\n  return config.schema\n    ? parseIntegrationConfigSchema(integration, config.schema, value)\n    : (value as TConfig);\n}\n\nfunction createIntegrationLifecycleLogger(\n  integration: FarmIntegration<any, any>,\n  phase: FarmIntegrationLogPhase,\n): FarmIntegrationLifecycleLogger {\n  const write = (\n    level: FarmIntegrationLifecycleLogLevel,\n    message: string,\n    meta?: Record<string, unknown>,\n  ) => {\n    if (!integration.log) {\n      return;\n    }\n\n    void Promise.resolve(\n      integration.log({\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase,\n        level,\n        message,\n        meta,\n        context: new Map(),\n      }),\n    ).catch(() => {});\n  };\n\n  return {\n    info(message, meta) {\n      write(\"info\", message, meta);\n    },\n    warn(message, meta) {\n      write(\"warn\", message, meta);\n    },\n    error(message, meta) {\n      write(\"error\", message, meta);\n    },\n  };\n}\n\nasync function emitIntegrationLog(\n  integration: FarmIntegration,\n  event: FarmIntegrationLogEvent,\n): Promise<void> {\n  try {\n    await integration.log?.(event);\n  } catch {\n    // Integration logging is optional observability. A failed sink must not\n    // block lifecycle startup, request handlers, responses, or cleanup.\n  }\n}\n\nconst INTEGRATION_DATA_HEADER = \"x-farm-integration-data\";\nconst INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;\nconst BLOCKED_INTEGRATION_DATA_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isFarmIntegrationData(value: unknown): value is FarmIntegrationData {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isPlainIntegrationDataObject(value: unknown): value is Record<string, unknown> {\n  if (!isFarmIntegrationData(value)) {\n    return false;\n  }\n\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction sanitizeIntegrationDataValue(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map((item) => sanitizeIntegrationDataValue(item));\n  }\n\n  if (!isPlainIntegrationDataObject(value)) {\n    return value;\n  }\n\n  const sanitized: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {\n      continue;\n    }\n\n    sanitized[key] = sanitizeIntegrationDataValue(item);\n  }\n\n  return sanitized;\n}\n\nfunction normalizeIntegrationData(value: FarmIntegrationData | undefined): FarmIntegrationData {\n  if (!isFarmIntegrationData(value)) {\n    return {};\n  }\n\n  const sanitized = sanitizeIntegrationDataValue(value);\n  return isFarmIntegrationData(sanitized) ? sanitized : {};\n}\n\nfunction getIntegrationDataHeaderByteLength(value: string): number {\n  return new TextEncoder().encode(value).byteLength;\n}\n\nfunction parseIntegrationDataHeader(request: Request): FarmIntegrationData {\n  const raw = request.headers.get(INTEGRATION_DATA_HEADER);\n  if (!raw) {\n    return {};\n  }\n\n  if (getIntegrationDataHeaderByteLength(raw) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {\n    return {};\n  }\n\n  try {\n    const value = JSON.parse(raw);\n    return normalizeIntegrationData(value);\n  } catch {\n    return {};\n  }\n}\n\nfunction resolveIntegrationData(request: Request, data?: FarmIntegrationData): FarmIntegrationData {\n  return {\n    ...parseIntegrationDataHeader(request),\n    ...normalizeIntegrationData(data),\n  };\n}\n\nfunction createIntegrationPlugin(integrationKey: string, integration: FarmIntegration): FarmPlugin {\n  const routes = normalizeIntegrationRoutes(integration.routes || []);\n  const middleware = [...(integration.middleware || [])];\n  const cleanupCallbacks: IntegrationLifecycleCleanup[] = [];\n  let integrationConfigPromise: Promise<unknown> | undefined;\n\n  const runCleanup = async () => {\n    const callbacks = cleanupCallbacks.splice(0).reverse();\n    for (const callback of callbacks) {\n      await callback();\n    }\n  };\n\n  const createLifecycleContext = async (\n    context: FarmPluginContext,\n    phase: FarmIntegrationLogPhase,\n    options: { reason?: string } = {},\n  ): Promise<FarmIntegrationLifecycleContext> => {\n    const args = createIntegrationRouteArgs({\n      integration,\n      config: context.config,\n    });\n    const configContext: FarmIntegrationConfigContext = {\n      key: integrationKey,\n      integration,\n      appConfig: context.config,\n      config: context.config,\n      args,\n      env: getIntegrationRuntimeEnv(),\n      isDev: context.isDev,\n      isProd: context.isProd,\n    };\n    integrationConfigPromise ??= resolveIntegrationConfig(integration, configContext);\n\n    return {\n      ...configContext,\n      integrationConfig: await integrationConfigPromise,\n      log: createIntegrationLifecycleLogger(integration, phase),\n      reason: options.reason,\n      async cleanup(callback) {\n        if (callback) {\n          cleanupCallbacks.push(callback);\n          return;\n        }\n\n        await runCleanup();\n      },\n    };\n  };\n\n  const plugin: FarmPlugin = {\n    name: `farm:integration:${integration.category}:${integration.type}`,\n    enforce: \"pre\",\n\n    async init(context) {\n      getIntegrationRuntimeRegistry().set(integrationKey, {\n        integration,\n        config: context.config,\n        isDev: context.isDev,\n        isProd: context.isProd,\n      });\n\n      await createLifecycleContext(context, \"validate\");\n\n      if (integration.validate) {\n        await integration.validate(await createLifecycleContext(context, \"validate\"));\n      }\n\n      if (integration.setup) {\n        await integration.setup(await createLifecycleContext(context, \"setup\"));\n      }\n\n      if (!integration.log) {\n        return;\n      }\n\n      for (const route of routes) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"registered\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          context: new Map(),\n        });\n      }\n\n      for (const entry of middleware) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"registered\",\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          context: new Map(),\n        });\n      }\n    },\n\n    async ready(context) {\n      if (integration.ready) {\n        await integration.ready(await createLifecycleContext(context, \"ready\"));\n      }\n    },\n\n    async shutdown(payload, context) {\n      try {\n        if (integration.dispose) {\n          await integration.dispose(\n            await createLifecycleContext(context, \"dispose\", {\n              reason: payload.reason,\n            }),\n          );\n        }\n      } finally {\n        await runCleanup();\n      }\n    },\n\n    async beforeRequest(req, res, context) {\n      const fullUrl = `http://${req.headers.host || \"localhost\"}${req.url || \"/\"}`;\n      const url = new URL(fullUrl);\n      const pathname = url.pathname;\n      const requestId = getRequestId(req);\n      let bodyLoaded = false;\n      let requestBody: Buffer | undefined;\n\n      const getRequestBody = async () => {\n        if (!bodyLoaded) {\n          bodyLoaded = true;\n          if (req.method && req.method !== \"GET\" && req.method !== \"HEAD\") {\n            requestBody = await readNodeRequestBody(\n              req,\n              resolveFarmServerConfig(context.config.server).bodySizeLimit,\n            );\n          }\n        }\n\n        return requestBody;\n      };\n\n      const createHandlerRequest = async (): Promise<Request | null> => {\n        try {\n          return createWebRequest(req, fullUrl, await getRequestBody());\n        } catch (error) {\n          const response = createFarmRequestBodyErrorResponse(error);\n          if (!response) throw error;\n          await sendWebResponse(res, response);\n          return null;\n        }\n      };\n\n      for (const entry of middleware) {\n        const params = resolveMatcherParams(entry.matcher, pathname);\n        if (!params) {\n          continue;\n        }\n\n        const request = await createHandlerRequest();\n        if (!request) return;\n        const handlerContext = createIntegrationHandlerContext({\n          integration,\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          request,\n          rawRequest: req,\n          params,\n          pathname,\n          requestId,\n          pluginContext: context,\n        });\n        const startedAt = Date.now();\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:start\",\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          request,\n          requestId,\n          context: handlerContext.req.snapshot(),\n        });\n\n        try {\n          const response = await entry.handler(request, handlerContext);\n\n          // A middleware that returns `void` lets the request continue to the\n          // downstream route/page handler, so its rotated `Set-Cookie` values\n          // cannot ride on its own response. It hands them to the runtime via\n          // forwardIntegrationSetCookies; merge them onto the Node response now\n          // (appending, so a later short-circuit Response or the page renderer\n          // can add its own Set-Cookie without dropping these). Read-and-clear\n          // so multiple middleware for one request each forward at most once.\n          const forwardedCookies = takeForwardedIntegrationSetCookies(handlerContext);\n          if (forwardedCookies.length > 0) {\n            const setCookieHeaders = new Headers();\n            for (const cookie of forwardedCookies) {\n              setCookieHeaders.append(\"set-cookie\", cookie);\n            }\n            applyWebResponseHeaders(res, setCookieHeaders, { appendSetCookie: true });\n          }\n\n          if (response) {\n            await sendWebResponse(res, response);\n            await emitIntegrationLog(integration, {\n              category: integration.category,\n              slot: integration.category,\n              type: integration.type,\n              phase: \"request:end\",\n              route: {\n                kind: \"middleware\",\n                path: normalizeMatcher(entry.matcher),\n                methods: [\"ALL\"],\n              },\n              request,\n              response,\n              requestId,\n              durationMs: Date.now() - startedAt,\n              context: handlerContext.req.snapshot(),\n            });\n            return;\n          }\n\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:end\",\n            route: {\n              kind: \"middleware\",\n              path: normalizeMatcher(entry.matcher),\n              methods: [\"ALL\"],\n            },\n            request,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            context: handlerContext.req.snapshot(),\n          });\n        } catch (error) {\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:error\",\n            route: {\n              kind: \"middleware\",\n              path: normalizeMatcher(entry.matcher),\n              methods: [\"ALL\"],\n            },\n            request,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            error,\n            context: handlerContext.req.snapshot(),\n          });\n          throw error;\n        }\n      }\n\n      for (const route of routes) {\n        const params = matchesMethod(route.methods, req.method)\n          ? extractPathParams(route.path, pathname)\n          : null;\n        if (!params) {\n          continue;\n        }\n\n        const request = await createHandlerRequest();\n        if (!request) return;\n        const handlerContext = createIntegrationHandlerContext({\n          integration,\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          rawRequest: req,\n          params,\n          pathname,\n          requestId,\n          pluginContext: context,\n        });\n        const startedAt = Date.now();\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:start\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          requestId,\n          context: handlerContext.req.snapshot(),\n        });\n\n        try {\n          const validation = await validateIntegrationRouteInput(route, request, url);\n          if (!validation.success) {\n            await sendWebResponse(res, validation.response);\n            await emitIntegrationLog(integration, {\n              category: integration.category,\n              slot: integration.category,\n              type: integration.type,\n              phase: \"request:end\",\n              route: {\n                kind: \"route\",\n                path: route.path,\n                methods: route.methods,\n              },\n              request,\n              response: validation.response,\n              requestId,\n              durationMs: Date.now() - startedAt,\n              context: handlerContext.req.snapshot(),\n            });\n            return;\n          }\n          handlerContext.input = validation.input;\n\n          for (const middlewareEntry of route.middleware || []) {\n            const middlewareResponse = await middlewareEntry.handler(request, handlerContext);\n            if (middlewareResponse) {\n              await sendWebResponse(res, middlewareResponse);\n              await emitIntegrationLog(integration, {\n                category: integration.category,\n                slot: integration.category,\n                type: integration.type,\n                phase: \"request:end\",\n                route: {\n                  kind: \"route\",\n                  path: route.path,\n                  methods: route.methods,\n                },\n                request,\n                response: middlewareResponse,\n                requestId,\n                durationMs: Date.now() - startedAt,\n                context: handlerContext.req.snapshot(),\n              });\n              return;\n            }\n          }\n\n          const beforeResponse = await runIntegrationRouteBeforeHooks(\n            route,\n            request,\n            handlerContext,\n          );\n          if (beforeResponse) {\n            const response = await runIntegrationRouteAfterHooks(\n              route,\n              request,\n              handlerContext,\n              beforeResponse,\n            );\n            await sendWebResponse(res, response);\n            await emitIntegrationLog(integration, {\n              category: integration.category,\n              slot: integration.category,\n              type: integration.type,\n              phase: \"request:end\",\n              route: {\n                kind: \"route\",\n                path: route.path,\n                methods: route.methods,\n              },\n              request,\n              response,\n              requestId,\n              durationMs: Date.now() - startedAt,\n              context: handlerContext.req.snapshot(),\n            });\n            return;\n          }\n\n          const handlerResponse = await route.handler(request, handlerContext);\n          const response = await runIntegrationRouteAfterHooks(\n            route,\n            request,\n            handlerContext,\n            handlerResponse,\n          );\n          await sendWebResponse(res, response);\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:end\",\n            route: {\n              kind: \"route\",\n              path: route.path,\n              methods: route.methods,\n            },\n            request,\n            response,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            context: handlerContext.req.snapshot(),\n          });\n          return;\n        } catch (error) {\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:error\",\n            route: {\n              kind: \"route\",\n              path: route.path,\n              methods: route.methods,\n            },\n            request,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            error,\n            context: handlerContext.req.snapshot(),\n          });\n          throw error;\n        }\n      }\n    },\n  };\n\n  Object.defineProperty(plugin, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME, {\n    value: integration.serverRuntime !== false,\n  });\n\n  return plugin;\n}\n\nfunction createIntegrationHandlerContext(input: {\n  integration: FarmIntegration;\n  route: FarmIntegrationHandlerContext[\"route\"];\n  request: Request;\n  rawRequest: FarmRequest;\n  params: FarmIntegrationRouteParams;\n  pathname: string;\n  requestId: string;\n  pluginContext: FarmPluginContext;\n}): FarmIntegrationHandlerContext {\n  const req = createIntegrationRequestContextStore(\n    input.rawRequest,\n    input.request,\n    input.pluginContext,\n  );\n\n  return {\n    request: input.request,\n    requestId: input.requestId,\n    url: new URL(input.request.url),\n    pathname: input.pathname,\n    method: input.request.method,\n    params: input.params,\n    input: {},\n    args: createIntegrationRouteArgs({\n      integration: input.integration,\n      config: input.pluginContext.config,\n    }),\n    data: resolveIntegrationData(input.request),\n    integration: {\n      category: input.integration.category,\n      slot: input.integration.category,\n      type: input.integration.type,\n      instance: input.integration.instance,\n    },\n    route: input.route,\n    req,\n    requestContext: req,\n    config: input.pluginContext.config,\n    isDev: input.pluginContext.isDev,\n    isProd: input.pluginContext.isProd,\n  };\n}\n\ntype NormalizedIntegrationRoute = Omit<FarmIntegrationRoute, \"method\" | \"methods\"> & {\n  methods: readonly string[];\n  __operation?: FarmIntegrationAPIOperation<any, any, any, any, any>;\n};\n\nfunction normalizeIntegrationRoutes(\n  routes: readonly FarmIntegrationRoute[],\n): NormalizedIntegrationRoute[] {\n  return routes\n    .map((route, index) => {\n      // Raw FarmIntegration objects and direct dispatch also pass through here.\n      assertUniqueRouteParameters(route.path, \"api\");\n      return {\n        index,\n        route: {\n          ...route,\n          methods: normalizeIntegrationRouteMethods(route),\n          input: normalizeIntegrationRouteInputSchemas(route),\n        },\n        specificity: getRoutePatternSpecificity(route.path, \"api\"),\n      };\n    })\n    .sort(\n      (left, right) =>\n        compareRouteSpecificity(left.specificity, right.specificity) || left.index - right.index,\n    )\n    .map(({ route }) => route);\n}\n\nfunction normalizeIntegrationRouteMethods(route: Pick<FarmIntegrationRoute, \"method\" | \"methods\">) {\n  const input =\n    route.methods && route.methods.length > 0\n      ? [...route.methods]\n      : route.method\n        ? [route.method]\n        : [\"ALL\"];\n\n  return input.map((method) => String(method).toUpperCase());\n}\n\nfunction normalizeIntegrationRouteInputSchemas<TBody, TQuery>(\n  route: Pick<FarmIntegrationRoute<TBody, TQuery>, \"body\" | \"query\" | \"input\">,\n): FarmIntegrationRouteInputSchemas<TBody, TQuery> | undefined {\n  const input: FarmIntegrationRouteInputSchemas<TBody, TQuery> = {\n    ...route.input,\n  };\n\n  if (route.body) {\n    input.body = route.body;\n  }\n\n  if (route.query) {\n    input.query = route.query;\n  }\n\n  return input.body || input.query ? input : undefined;\n}\n\ntype IntegrationRouteInputValidationResult =\n  | {\n      success: true;\n      input: FarmIntegrationRouteInput;\n    }\n  | {\n      success: false;\n      response: Response;\n    };\n\nasync function validateIntegrationRouteInput(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  url: URL,\n): Promise<IntegrationRouteInputValidationResult> {\n  if (request.method.toUpperCase() === \"QUERY\" && !request.headers.has(\"content-type\")) {\n    return {\n      success: false,\n      response: Response.json(\n        {\n          error: \"Invalid QUERY request\",\n          message: \"QUERY requests must include a Content-Type header.\",\n        },\n        { status: 400 },\n      ),\n    };\n  }\n\n  const schemas = route.input;\n  if (!schemas?.body && !schemas?.query) {\n    return {\n      success: true,\n      input: {},\n    };\n  }\n\n  const input: FarmIntegrationRouteInput = {};\n  const issues: FarmIntegrationValidationIssue[] = [];\n\n  if (schemas.query) {\n    const queryResult = await parseIntegrationInputSchema(\n      \"query\",\n      schemas.query,\n      createQueryInput(url.searchParams),\n    );\n    if (queryResult.success) {\n      input.query = queryResult.data;\n    } else {\n      issues.push(...queryResult.issues);\n    }\n  }\n\n  if (schemas.body) {\n    const bodyInput = await readIntegrationValidationBody(\n      request,\n      getIntegrationRouteBodyFormat(route),\n    );\n\n    if (bodyInput.success) {\n      const bodyResult = await parseIntegrationInputSchema(\"body\", schemas.body, bodyInput.data);\n      if (bodyResult.success) {\n        input.body = bodyResult.data;\n      } else {\n        issues.push(...bodyResult.issues);\n      }\n    } else {\n      issues.push(bodyInput.issue);\n    }\n  }\n\n  if (issues.length > 0) {\n    return {\n      success: false,\n      response: createIntegrationValidationResponse(issues),\n    };\n  }\n\n  return {\n    success: true,\n    input,\n  };\n}\n\nasync function parseIntegrationInputSchema<TValue>(\n  source: FarmIntegrationRouteInputSource,\n  schema: FarmIntegrationInputSchema<TValue>,\n  value: unknown,\n): Promise<\n  | {\n      success: true;\n      data: TValue;\n    }\n  | {\n      success: false;\n      issues: FarmIntegrationValidationIssue[];\n    }\n> {\n  const parser = schema.safeParseAsync || schema.safeParse;\n  if (parser) {\n    const result = await parser.call(schema, value);\n    if (result.success) {\n      return {\n        success: true,\n        data: result.data,\n      };\n    }\n\n    return {\n      success: false,\n      issues: normalizeIntegrationValidationIssues(source, result.error),\n    };\n  }\n\n  if (schema[\"~standard\"]?.validate) {\n    const result = await schema[\"~standard\"].validate(value);\n    if (\"value\" in result) {\n      return {\n        success: true,\n        data: result.value,\n      };\n    }\n\n    return {\n      success: false,\n      issues: normalizeIntegrationValidationIssues(source, {\n        issues: result.issues,\n      }),\n    };\n  }\n\n  if (schema.parse) {\n    try {\n      return {\n        success: true,\n        data: await schema.parse(value),\n      };\n    } catch (error) {\n      return {\n        success: false,\n        issues: normalizeIntegrationValidationIssues(\n          source,\n          normalizeIntegrationValidationError(error),\n        ),\n      };\n    }\n  }\n\n  return {\n    success: false,\n    issues: [\n      {\n        source,\n        message:\n          \"Input schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.\",\n      },\n    ],\n  };\n}\n\nfunction createIntegrationValidationResponse(issues: readonly FarmIntegrationValidationIssue[]) {\n  return Response.json(\n    {\n      error: \"Integration route input validation failed\",\n      issues,\n    },\n    {\n      status: 400,\n    },\n  );\n}\n\nfunction normalizeIntegrationValidationIssues(\n  source: FarmIntegrationRouteInputSource,\n  error: FarmIntegrationValidationErrorLike,\n): FarmIntegrationValidationIssue[] {\n  if (Array.isArray(error.issues) && error.issues.length > 0) {\n    return error.issues.map((issue) => ({\n      source,\n      path: normalizeIntegrationValidationPath(issue.path),\n      code: issue.code,\n      message: issue.message || \"Invalid input\",\n    }));\n  }\n\n  return [\n    {\n      source,\n      path: [],\n      message: error.message || \"Invalid input\",\n    },\n  ];\n}\n\nfunction normalizeIntegrationValidationPath(\n  path: readonly FarmIntegrationValidationPathSegment[] | undefined,\n): (string | number)[] {\n  return (path || []).map((segment) => {\n    const key =\n      typeof segment === \"object\" && segment !== null && \"key\" in segment ? segment.key : segment;\n    return typeof key === \"symbol\" ? key.description || key.toString() : key;\n  });\n}\n\nfunction normalizeIntegrationValidationError(error: unknown): FarmIntegrationValidationErrorLike {\n  if (error && typeof error === \"object\") {\n    return error as FarmIntegrationValidationErrorLike;\n  }\n\n  return {\n    message: error instanceof Error ? error.message : String(error || \"Invalid input\"),\n  };\n}\n\nasync function readIntegrationValidationBody(\n  request: Request,\n  format: FarmIntegrationAPIBodyFormat,\n): Promise<\n  | {\n      success: true;\n      data: unknown;\n    }\n  | {\n      success: false;\n      issue: FarmIntegrationValidationIssue;\n    }\n> {\n  if (request.method === \"GET\" || request.method === \"HEAD\" || format === \"none\") {\n    return {\n      success: true,\n      data: undefined,\n    };\n  }\n\n  try {\n    if (format === \"form\") {\n      return {\n        success: true,\n        data: createFormInput(await request.clone().formData()),\n      };\n    }\n\n    const text = await request.clone().text();\n    if (text.trim().length === 0) {\n      return {\n        success: true,\n        data: undefined,\n      };\n    }\n\n    return {\n      success: true,\n      data: JSON.parse(text),\n    };\n  } catch (error) {\n    return {\n      success: false,\n      issue: {\n        source: \"body\",\n        path: [],\n        message:\n          format === \"json\"\n            ? \"Expected a valid JSON request body.\"\n            : error instanceof Error && error.message\n              ? error.message\n              : \"Could not parse request body.\",\n      },\n    };\n  }\n}\n\nfunction getIntegrationRouteBodyFormat(route: NormalizedIntegrationRoute) {\n  return route.bodyFormat || route.__operation?.bodyFormat || \"json\";\n}\n\nfunction createIntegrationRouteArgs(input: {\n  integration: FarmIntegration;\n  config: FarmPluginContext[\"config\"];\n}): FarmIntegrationRouteArgs {\n  let clientPromise: Promise<unknown | undefined> | undefined;\n  let ormPromise: Promise<unknown> | undefined;\n\n  const getClient = () => {\n    clientPromise ??= import(\"./storage\").then(({ resolveStorageRuntimeClient }) =>\n      resolveStorageRuntimeClient(input.config.storage),\n    );\n    return clientPromise;\n  };\n\n  const getOrm = () => {\n    if (!input.integration.schema) {\n      throw new Error(\n        `Integration \"${input.integration.type}\" does not define a schema for ctx.args.db.`,\n      );\n    }\n\n    ormPromise ??= import(\"./integration-orm\").then(({ createIntegrationOrm }) =>\n      createIntegrationOrm({\n        schema: input.integration.schema!,\n        config: input.config,\n      }),\n    );\n    return ormPromise;\n  };\n\n  return {\n    db: createLazyIntegrationOrmClient(getOrm) as never,\n    getDb: getOrm as never,\n    storage: {\n      getClient,\n      getOrm: getOrm as never,\n    },\n  };\n}\n\nfunction createLazyIntegrationOrmClient(resolveOrm: () => Promise<unknown>) {\n  const modelProxyCache = new Map<PropertyKey, unknown>();\n\n  return new Proxy(\n    {},\n    {\n      get(_target, prop) {\n        if (prop === \"then\") {\n          return undefined;\n        }\n\n        if (prop === \"transaction\" || prop === \"batch\") {\n          return async (...args: unknown[]) => {\n            const orm = (await resolveOrm()) as Record<PropertyKey, unknown>;\n            const member = orm[prop];\n            if (typeof member !== \"function\") {\n              throw new Error(`Integration ORM does not expose \"${String(prop)}\".`);\n            }\n            return member.apply(orm, args);\n          };\n        }\n\n        if (prop === \"$driver\") {\n          return undefined;\n        }\n\n        if (!modelProxyCache.has(prop)) {\n          modelProxyCache.set(prop, createLazyIntegrationOrmModel(resolveOrm, prop));\n        }\n\n        return modelProxyCache.get(prop);\n      },\n    },\n  );\n}\n\nfunction createLazyIntegrationOrmModel(resolveOrm: () => Promise<unknown>, modelName: PropertyKey) {\n  return new Proxy(\n    {},\n    {\n      get(_target, prop) {\n        if (prop === \"then\") {\n          return undefined;\n        }\n\n        return async (...args: unknown[]) => {\n          const orm = (await resolveOrm()) as Record<PropertyKey, Record<PropertyKey, unknown>>;\n          const model = orm[modelName];\n          const member = model?.[prop];\n          if (typeof member !== \"function\") {\n            throw new Error(\n              `Integration ORM model \"${String(modelName)}\" does not expose \"${String(prop)}\".`,\n            );\n          }\n          return member.apply(model, args);\n        };\n      },\n    },\n  );\n}\n\nasync function runIntegrationRouteBeforeHooks(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  context: FarmIntegrationHandlerContext,\n): Promise<Response | undefined> {\n  const hookContext = context as FarmIntegrationRouteHookContext;\n  hookContext.response = undefined;\n\n  for (const hook of route.before || []) {\n    const response = await hook(request, hookContext);\n    if (response) {\n      hookContext.response = response;\n      return response;\n    }\n\n    if (hookContext.response) {\n      return hookContext.response;\n    }\n  }\n\n  return undefined;\n}\n\nasync function runIntegrationRouteAfterHooks(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  context: FarmIntegrationHandlerContext,\n  response: Response,\n): Promise<Response> {\n  const hookContext = context as FarmIntegrationRouteHookContext;\n  let currentResponse = response;\n\n  for (const hook of route.after || []) {\n    hookContext.response = currentResponse;\n    const nextResponse = await hook(request, hookContext);\n    currentResponse = nextResponse || hookContext.response || currentResponse;\n  }\n\n  hookContext.response = currentResponse;\n  return currentResponse;\n}\n\nfunction createQueryInput(searchParams: URLSearchParams): Record<string, string | string[]> {\n  const input: Record<string, string | string[]> = {};\n  searchParams.forEach((value, key) => {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return;\n\n    const existing = input[key];\n    if (existing === undefined) {\n      input[key] = value;\n      return;\n    }\n\n    input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n  });\n  return input;\n}\n\nfunction createFormInput(\n  formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n  const input: Record<string, FormDataEntryValue | FormDataEntryValue[]> = {};\n  formData.forEach((value, key) => {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return;\n\n    const existing = input[key];\n    if (existing === undefined) {\n      input[key] = value;\n      return;\n    }\n\n    input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n  });\n  return input;\n}\n\nexport async function dispatchIntegrationRequest(\n  runtime: RegisteredIntegrationRuntime,\n  request: Request,\n  options: {\n    currentRequest?: Request;\n    data?: FarmIntegrationData;\n    internal?: boolean;\n  } = {},\n): Promise<Response | null> {\n  try {\n    request = await bufferFarmRequestBody(\n      request,\n      resolveFarmServerConfig(runtime.config.server).bodySizeLimit,\n    );\n  } catch (error) {\n    const response = createFarmRequestBodyErrorResponse(error);\n    if (response) return response;\n    throw error;\n  }\n\n  const integration = runtime.integration;\n  const url = new URL(request.url);\n  const pathname = url.pathname;\n  const requestId =\n    request.headers.get(\"x-request-id\") ||\n    options.currentRequest?.headers.get(\"x-request-id\") ||\n    String(Date.now());\n  const routes = normalizeIntegrationRoutes(integration.routes || []);\n  const middleware = [...(integration.middleware || [])];\n\n  // Cookies an integration middleware forwards via forwardIntegrationSetCookies\n  // while returning `void` (letting the request continue). They are merged onto\n  // whichever Response this dispatch ultimately returns so a server-side\n  // refresh/rotation reaches the browser instead of being dropped. Top-level\n  // and per-route middleware both contribute here; read-and-clear keeps each\n  // batch applied at most once.\n  const forwardedSetCookies: string[] = [];\n\n  for (const entry of middleware) {\n    const params = resolveMatcherParams(entry.matcher, pathname);\n    if (!params) {\n      continue;\n    }\n\n    const handlerContext = createServerIntegrationHandlerContext({\n      runtime,\n      route: {\n        kind: \"middleware\",\n        path: normalizeMatcher(entry.matcher),\n        methods: [\"ALL\"],\n      },\n      request,\n      params,\n      pathname,\n      requestId,\n      currentRequest: options.currentRequest,\n      data: options.data,\n      internal: options.internal === true,\n    });\n    const startedAt = Date.now();\n\n    await emitIntegrationLog(integration, {\n      category: integration.category,\n      slot: integration.category,\n      type: integration.type,\n      phase: \"request:start\",\n      route: {\n        kind: \"middleware\",\n        path: normalizeMatcher(entry.matcher),\n        methods: [\"ALL\"],\n      },\n      request,\n      requestId,\n      context: handlerContext.req.snapshot(),\n    });\n\n    try {\n      const response = await entry.handler(request, handlerContext);\n      forwardedSetCookies.push(...takeForwardedIntegrationSetCookies(handlerContext));\n      if (response) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:end\",\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          request,\n          response,\n          requestId,\n          durationMs: Date.now() - startedAt,\n          context: handlerContext.req.snapshot(),\n        });\n        return appendIntegrationForwardedCookies(response, forwardedSetCookies);\n      }\n\n      await emitIntegrationLog(integration, {\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase: \"request:end\",\n        route: {\n          kind: \"middleware\",\n          path: normalizeMatcher(entry.matcher),\n          methods: [\"ALL\"],\n        },\n        request,\n        requestId,\n        durationMs: Date.now() - startedAt,\n        context: handlerContext.req.snapshot(),\n      });\n    } catch (error) {\n      await emitIntegrationLog(integration, {\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase: \"request:error\",\n        route: {\n          kind: \"middleware\",\n          path: normalizeMatcher(entry.matcher),\n          methods: [\"ALL\"],\n        },\n        request,\n        requestId,\n        durationMs: Date.now() - startedAt,\n        error,\n        context: handlerContext.req.snapshot(),\n      });\n      throw error;\n    }\n  }\n\n  for (const route of routes) {\n    const params = matchesMethod(route.methods, request.method)\n      ? extractPathParams(route.path, pathname)\n      : null;\n    if (!params) {\n      continue;\n    }\n\n    const handlerContext = createServerIntegrationHandlerContext({\n      runtime,\n      route: {\n        kind: \"route\",\n        path: route.path,\n        methods: route.methods,\n      },\n      request,\n      params,\n      pathname,\n      requestId,\n      currentRequest: options.currentRequest,\n      data: options.data,\n      internal: options.internal === true,\n    });\n    const startedAt = Date.now();\n\n    await emitIntegrationLog(integration, {\n      category: integration.category,\n      slot: integration.category,\n      type: integration.type,\n      phase: \"request:start\",\n      route: {\n        kind: \"route\",\n        path: route.path,\n        methods: route.methods,\n      },\n      request,\n      requestId,\n      context: handlerContext.req.snapshot(),\n    });\n\n    try {\n      const validation = await validateIntegrationRouteInput(route, request, url);\n      if (!validation.success) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:end\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          response: validation.response,\n          requestId,\n          durationMs: Date.now() - startedAt,\n          context: handlerContext.req.snapshot(),\n        });\n        return appendIntegrationForwardedCookies(validation.response, forwardedSetCookies);\n      }\n      handlerContext.input = validation.input;\n\n      for (const middlewareEntry of route.middleware || []) {\n        const middlewareResponse = await middlewareEntry.handler(request, handlerContext);\n        forwardedSetCookies.push(...takeForwardedIntegrationSetCookies(handlerContext));\n        if (middlewareResponse) {\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:end\",\n            route: {\n              kind: \"route\",\n              path: route.path,\n              methods: route.methods,\n            },\n            request,\n            response: middlewareResponse,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            context: handlerContext.req.snapshot(),\n          });\n          return appendIntegrationForwardedCookies(middlewareResponse, forwardedSetCookies);\n        }\n      }\n\n      const beforeResponse = await runIntegrationRouteBeforeHooks(route, request, handlerContext);\n      if (beforeResponse) {\n        const response = await runIntegrationRouteAfterHooks(\n          route,\n          request,\n          handlerContext,\n          beforeResponse,\n        );\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:end\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          response,\n          requestId,\n          durationMs: Date.now() - startedAt,\n          context: handlerContext.req.snapshot(),\n        });\n        return appendIntegrationForwardedCookies(response, forwardedSetCookies);\n      }\n\n      const handlerResponse = await route.handler(request, handlerContext);\n      const response = await runIntegrationRouteAfterHooks(\n        route,\n        request,\n        handlerContext,\n        handlerResponse,\n      );\n      await emitIntegrationLog(integration, {\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase: \"request:end\",\n        route: {\n          kind: \"route\",\n          path: route.path,\n          methods: route.methods,\n        },\n        request,\n        response,\n        requestId,\n        durationMs: Date.now() - startedAt,\n        context: handlerContext.req.snapshot(),\n      });\n      return appendIntegrationForwardedCookies(response, forwardedSetCookies);\n    } catch (error) {\n      await emitIntegrationLog(integration, {\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase: \"request:error\",\n        route: {\n          kind: \"route\",\n          path: route.path,\n          methods: route.methods,\n        },\n        request,\n        requestId,\n        durationMs: Date.now() - startedAt,\n        error,\n        context: handlerContext.req.snapshot(),\n      });\n      throw error;\n    }\n  }\n\n  return null;\n}\n\n(globalThis as GlobalWithIntegrationRuntimeRegistry)[INTEGRATION_REQUEST_DISPATCHER_KEY] =\n  dispatchIntegrationRequest;\n\nfunction createIntegrationRequestContextStore(\n  rawRequest: FarmRequest,\n  request: Request,\n  pluginContext: FarmPluginContext,\n): FarmIntegrationRequestContextStore {\n  return {\n    get(key) {\n      const requestValue = pluginContext.requestContext.get(request, key);\n      if (requestValue !== undefined) {\n        return requestValue;\n      }\n\n      return pluginContext.requestContext.get(rawRequest, key);\n    },\n    set(key, value, options) {\n      pluginContext.requestContext.set(rawRequest, key, value, options);\n      pluginContext.requestContext.set(request, key, value, options);\n    },\n    has(key) {\n      return (\n        pluginContext.requestContext.has(request, key) ||\n        pluginContext.requestContext.has(rawRequest, key)\n      );\n    },\n    delete(key) {\n      const deletedRequest = pluginContext.requestContext.delete(request, key);\n      const deletedRaw = pluginContext.requestContext.delete(rawRequest, key);\n      return deletedRequest || deletedRaw;\n    },\n    clear() {\n      pluginContext.requestContext.clear(rawRequest);\n      pluginContext.requestContext.clear(request);\n    },\n    snapshot(options) {\n      const merged = pluginContext.requestContext.getAll(rawRequest, options);\n      const requestSnapshot = pluginContext.requestContext.getAll(request, options);\n      for (const [key, value] of requestSnapshot) {\n        merged.set(key, value);\n      }\n      return merged;\n    },\n  };\n}\n\nfunction createServerIntegrationHandlerContext(input: {\n  runtime: RegisteredIntegrationRuntime;\n  route: FarmIntegrationHandlerContext[\"route\"];\n  request: Request;\n  params: FarmIntegrationRouteParams;\n  pathname: string;\n  requestId: string;\n  currentRequest?: Request;\n  data?: FarmIntegrationData;\n  internal?: boolean;\n}): FarmIntegrationHandlerContext {\n  const req = createServerIntegrationRequestContextStore(input.request, input.currentRequest);\n\n  if (input.internal) {\n    req.set(FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY, true);\n  }\n\n  return {\n    request: input.request,\n    requestId: input.requestId,\n    url: new URL(input.request.url),\n    pathname: input.pathname,\n    method: input.request.method,\n    params: input.params,\n    input: {},\n    args: createIntegrationRouteArgs({\n      integration: input.runtime.integration,\n      config: input.runtime.config,\n    }),\n    data: resolveIntegrationData(input.request, input.data),\n    integration: {\n      category: input.runtime.integration.category,\n      slot: input.runtime.integration.category,\n      type: input.runtime.integration.type,\n      instance: input.runtime.integration.instance,\n    },\n    route: input.route,\n    req,\n    requestContext: req,\n    config: input.runtime.config,\n    isDev: input.runtime.isDev,\n    isProd: input.runtime.isProd,\n  };\n}\n\nfunction createServerIntegrationRequestContextStore(\n  request: Request,\n  currentRequest?: Request,\n): FarmIntegrationRequestContextStore {\n  return {\n    get(key) {\n      const requestValue = getRequestContext(request, key);\n      if (requestValue !== undefined) {\n        return requestValue;\n      }\n\n      if (currentRequest) {\n        return getRequestContext(currentRequest, key);\n      }\n\n      return undefined;\n    },\n    set(key, value, options) {\n      setRequestContext(request, key, value, options);\n      if (currentRequest) {\n        setRequestContext(currentRequest, key, value, options);\n      }\n    },\n    has(key) {\n      return (\n        hasRequestContext(request, key) ||\n        (!!currentRequest && hasRequestContext(currentRequest, key))\n      );\n    },\n    delete(key) {\n      const deletedRequest = deleteRequestContext(request, key);\n      const deletedCurrent = currentRequest ? deleteRequestContext(currentRequest, key) : false;\n      return deletedRequest || deletedCurrent;\n    },\n    clear() {\n      clearRequestContext(request);\n      if (currentRequest) {\n        clearRequestContext(currentRequest);\n      }\n    },\n    snapshot(options) {\n      const merged = currentRequest\n        ? getRequestContextSnapshot(currentRequest, options)\n        : new Map<string, unknown>();\n      const requestSnapshot = getRequestContextSnapshot(request, options);\n      for (const [key, value] of requestSnapshot) {\n        merged.set(key, value);\n      }\n      return merged;\n    },\n  };\n}\n\nfunction createWebRequest(req: FarmRequest, fullUrl: string, body?: Buffer): Request {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        headers.append(key, item);\n      }\n      continue;\n    }\n\n    headers.set(key, value);\n  }\n\n  return new Request(fullUrl, {\n    method: req.method,\n    headers,\n    body: body as BodyInit | undefined,\n  });\n}\n\nfunction matchesMethod(methods: readonly string[], method: string | undefined): boolean {\n  if (!method) {\n    return false;\n  }\n\n  const normalizedMethod = method.toUpperCase();\n  return methods.some((item) => {\n    const candidate = item.toUpperCase();\n    return candidate === \"ALL\" || candidate === normalizedMethod;\n  });\n}\n\nfunction matchesMatcher(\n  matcher: string | readonly string[] | undefined,\n  pathname: string,\n): boolean {\n  return resolveMatcherParams(matcher, pathname) !== null;\n}\n\nfunction resolveMatcherParams(\n  matcher: string | readonly string[] | undefined,\n  pathname: string,\n): FarmIntegrationRouteParams | null {\n  if (!matcher) {\n    return {};\n  }\n\n  const list = Array.isArray(matcher) ? matcher : [matcher];\n  for (const item of list) {\n    if (item === \"/(.*)\" || item === \"*\") {\n      return {};\n    }\n    if (item.endsWith(\"(.*)\")) {\n      const prefix = item.slice(0, -4);\n      if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n        return {};\n      }\n      continue;\n    }\n    const params = extractPathParams(item, pathname);\n    if (params) {\n      return params;\n    }\n  }\n\n  return null;\n}\n\nfunction matchesPath(pattern: string, pathname: string): boolean {\n  return extractPathParams(pattern, pathname) !== null;\n}\n\nfunction extractPathParams(pattern: string, pathname: string): FarmIntegrationRouteParams | null {\n  const routeSegments = splitPath(pattern);\n  const pathSegments = splitPath(pathname);\n  const params: FarmIntegrationRouteParams = {};\n\n  let routeIndex = 0;\n  let pathIndex = 0;\n\n  while (routeIndex < routeSegments.length && pathIndex < pathSegments.length) {\n    const routeSegment = routeSegments[routeIndex];\n    const pathSegment = pathSegments[pathIndex];\n\n    if (isCatchAllSegment(routeSegment)) {\n      params[getSegmentParamName(routeSegment)] = pathSegments\n        .slice(pathIndex)\n        .map((segment) => decodeRouteSegment(segment));\n      return params;\n    }\n\n    if (isDynamicSegment(routeSegment)) {\n      params[getSegmentParamName(routeSegment)] = decodeRouteSegment(pathSegment);\n      routeIndex += 1;\n      pathIndex += 1;\n      continue;\n    }\n\n    if (routeSegment !== pathSegment) {\n      return null;\n    }\n\n    routeIndex += 1;\n    pathIndex += 1;\n  }\n\n  if (routeIndex === routeSegments.length && pathIndex === pathSegments.length) {\n    return params;\n  }\n\n  if (routeIndex === routeSegments.length - 1 && isCatchAllSegment(routeSegments[routeIndex])) {\n    params[getSegmentParamName(routeSegments[routeIndex])] = [];\n    return params;\n  }\n\n  return null;\n}\n\nfunction splitPath(value: string): string[] {\n  return value.split(\"/\").filter(Boolean);\n}\n\nfunction isDynamicSegment(segment: string): boolean {\n  return segment.startsWith(\"[\") && segment.endsWith(\"]\");\n}\n\nfunction isCatchAllSegment(segment: string): boolean {\n  return segment.startsWith(\"[...\") && segment.endsWith(\"]\");\n}\n\nfunction getSegmentParamName(segment: string): string {\n  if (isCatchAllSegment(segment)) {\n    return segment.slice(4, -1);\n  }\n\n  return segment.slice(1, -1);\n}\n\nfunction getRequestId(req: FarmRequest): string {\n  const headerValue = req.headers[\"x-request-id\"];\n  if (Array.isArray(headerValue)) {\n    return headerValue[0] || String(Date.now());\n  }\n  return headerValue || String(Date.now());\n}\n\nfunction normalizeMatcher(matcher: string | readonly string[] | undefined): string {\n  if (!matcher) {\n    return \"/(.*)\";\n  }\n  return typeof matcher === \"string\" ? matcher : matcher.join(\", \");\n}\n","import {\n  createFarmRequestBodyErrorResponse,\n  readFarmRequestBody,\n  resolveFarmServerConfig,\n  type FarmServerConfig,\n  type ResolvedFarmServerConfig,\n} from \"./server-http\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { farmSecretsMatch } from \"./secret-compare\";\nimport { isFarmDeployedRuntime, readFarmEnvironmentValue } from \"./utils/runtime-env\";\nimport { decodeRouteSegment } from \"./utils/decode\";\nimport { toPosixPath } from \"./utils\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport {\n  isAbsolute as isAbsolutePath,\n  normalize as normalizePath,\n  relative as relativeFilePath,\n  resolve as resolvePath,\n  sep as pathSeparator,\n} from \"node:path\";\n\nexport type FarmWorkflowSchedule = string | string[];\n\nexport interface FarmWorkflowsUserConfig {\n  /** Enable or disable Farm workflow discovery. Enabled by default. */\n  enabled?: boolean;\n  /** Directory or directories to scan for workflow modules. */\n  dir?: string | string[];\n  /** Alias for dir. */\n  dirs?: string[];\n  /** HTTP route used for manual and URL-based cron invocation. */\n  route?: string;\n  /** Environment variable that stores the optional runner secret. */\n  secretEnv?: string;\n  /** Inline runner secret. Prefer secretEnv for deployed apps. */\n  secret?: string;\n  /**\n   * Serve the workflow route without a secret in a deployed runtime.\n   * Defaults to false: without a secret the route is public, so production\n   * requests are rejected unless this is explicitly enabled.\n   */\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmWorkflowsResolvedConfig {\n  enabled: boolean;\n  dirs: string[];\n  route: string;\n  secretEnv: string;\n  secret?: string;\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmWorkflowLogger {\n  info: (...args: unknown[]) => void;\n  warn: (...args: unknown[]) => void;\n  error: (...args: unknown[]) => void;\n}\n\nexport interface FarmWorkflowRunContext<TPayload = unknown> {\n  id: string;\n  name: string;\n  payload: TPayload;\n  scheduledTime?: number | string;\n  request?: Request;\n  event?: unknown;\n  env: Record<string, string | undefined>;\n  data: Map<string, unknown>;\n  log: FarmWorkflowLogger;\n}\n\nexport interface FarmWorkflowDefinition<TPayload = unknown, TResult = unknown> {\n  kind?: \"farm-workflow\";\n  id?: string;\n  description?: string;\n  schedule?: FarmWorkflowSchedule;\n  timezone?: string;\n  run: (ctx: FarmWorkflowRunContext<TPayload>) => TResult | Promise<TResult>;\n}\n\nexport interface FarmCronDefinition<\n  TPayload = unknown,\n  TResult = unknown,\n> extends FarmWorkflowDefinition<TPayload, TResult> {\n  schedule: FarmWorkflowSchedule;\n}\n\nexport interface FarmDiscoveredWorkflow {\n  id: string;\n  filePath: string;\n  description?: string;\n  schedule: string[];\n  timezone?: string;\n  routePath: string;\n}\n\nexport interface PreparedFarmWorkflows {\n  workflows: FarmDiscoveredWorkflow[];\n  tasks: Record<string, { handler: string; description: string }>;\n  scheduledTasks: Record<string, string | string[]>;\n  handlerPath?: string;\n  manifestPath?: string;\n}\n\nexport interface FarmWorkflowHTTPHandlerOptions {\n  workflows: FarmDiscoveredWorkflow[];\n  config: FarmWorkflowsResolvedConfig;\n  loadModule: (workflow: FarmDiscoveredWorkflow) => Promise<Record<string, any>>;\n  server?: FarmServerConfig | ResolvedFarmServerConfig;\n}\n\nexport const DEFAULT_FARM_WORKFLOW_DIRS = [\"src/jobs\", \"src/workflows\", \"src/cron\"];\nexport const DEFAULT_FARM_WORKFLOW_ROUTE = \"/api/_farm/workflows\";\nexport const DEFAULT_FARM_WORKFLOW_SECRET_ENV = \"CRON_SECRET\";\nconst MISSING_FARM_WORKFLOW_SECRET_ERROR =\n  \"Workflow route requires a secret. Set the CRON_SECRET environment variable, configure workflows.secret, or set workflows.allowUnsecured to true.\";\n\nexport function defineWorkflow<const TPayload = unknown, TResult = unknown>(\n  definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n  return {\n    ...definition,\n    kind: \"farm-workflow\",\n  };\n}\n\nexport function defineTask<const TPayload = unknown, TResult = unknown>(\n  definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n  return defineWorkflow(definition);\n}\n\n/**\n * @deprecated Configure `cron` in `farm.config.ts` and point it at an API route.\n */\nexport function defineCron<const TPayload = unknown, TResult = unknown>(\n  definition: FarmCronDefinition<TPayload, TResult>,\n): FarmCronDefinition<TPayload, TResult> {\n  return {\n    ...definition,\n    kind: \"farm-workflow\",\n  };\n}\n\nexport function resolveWorkflowsConfig(\n  workflows: FarmWorkflowsUserConfig | boolean | undefined,\n): FarmWorkflowsResolvedConfig {\n  if (workflows === false) {\n    return {\n      enabled: false,\n      dirs: [...DEFAULT_FARM_WORKFLOW_DIRS],\n      route: DEFAULT_FARM_WORKFLOW_ROUTE,\n      secretEnv: DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n    };\n  }\n\n  const options = workflows && typeof workflows === \"object\" ? workflows : {};\n  const dirs = normalizeWorkflowDirs(options);\n\n  return {\n    enabled: options.enabled ?? true,\n    dirs,\n    route: normalizeWorkflowRoute(options.route || DEFAULT_FARM_WORKFLOW_ROUTE),\n    secretEnv: options.secretEnv || DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n    secret: options.secret,\n    allowUnsecured: options.allowUnsecured === true,\n  };\n}\n\nexport async function discoverFarmWorkflows(\n  config: {\n    root?: string;\n    workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean;\n  },\n  options: {\n    loadModule?: (filePath: string) => Promise<Record<string, any>>;\n  } = {},\n): Promise<FarmDiscoveredWorkflow[]> {\n  const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n    ? config.workflows\n    : resolveWorkflowsConfig(config.workflows);\n  if (!workflowConfig.enabled) return [];\n\n  const root = config.root || process.cwd();\n  const files = await findWorkflowFiles(root, workflowConfig.dirs);\n  const workflows: FarmDiscoveredWorkflow[] = [];\n  const seenIds = new Map<string, string>();\n\n  for (const filePath of files) {\n    const module = options.loadModule\n      ? await options.loadModule(filePath)\n      : await loadWorkflowModule(filePath, root);\n    const definition = resolveWorkflowDefinition(module);\n    if (!definition) continue;\n\n    const id = normalizeWorkflowId(\n      definition.id || workflowIdFromFile(root, workflowConfig.dirs, filePath),\n    );\n    const previousPath = seenIds.get(id);\n    if (previousPath) {\n      throw new Error(\n        `Duplicate Farm workflow id \"${id}\" found in ${relativePath(root, previousPath)} and ${relativePath(root, filePath)}.`,\n      );\n    }\n    seenIds.set(id, filePath);\n\n    workflows.push({\n      id,\n      filePath,\n      description: definition.description,\n      schedule: normalizeSchedule(definition.schedule),\n      timezone: definition.timezone,\n      routePath: joinRoute(workflowConfig.route, encodeURIComponent(id)),\n    });\n  }\n\n  return workflows;\n}\n\nexport function createFarmWorkflowRequestHandler(options: FarmWorkflowHTTPHandlerOptions) {\n  const workflowsById = new Map(options.workflows.map((workflow) => [workflow.id, workflow]));\n\n  return async function handleFarmWorkflowRequest(request: Request): Promise<Response | null> {\n    const url = new URL(request.url);\n    const route = normalizeWorkflowRoute(options.config.route);\n    if (url.pathname !== route && !url.pathname.startsWith(`${route}/`)) {\n      return null;\n    }\n\n    if (url.pathname === route) {\n      const secretError = verifyWorkflowSecret(request, options.config);\n      if (secretError) return secretError;\n\n      return Response.json({\n        workflows: options.workflows.map(toWorkflowMetadata),\n      });\n    }\n\n    const id = decodeRouteSegment(url.pathname.slice(route.length + 1));\n\n    // Verify the secret before consulting the workflow id map so the\n    // existing-vs-missing distinction is not disclosed to callers without\n    // the secret (a 401 for unknown ids would otherwise become a 404 oracle).\n    const secretError = verifyWorkflowSecret(request, options.config);\n    if (secretError) return secretError;\n\n    const workflow = workflowsById.get(id);\n    if (!workflow) {\n      return Response.json({ error: `Workflow \"${id}\" was not found.` }, { status: 404 });\n    }\n\n    let payload: unknown;\n    try {\n      payload = await readWorkflowPayload(\n        request,\n        resolveFarmServerConfig(options.server).bodySizeLimit,\n      );\n    } catch (error) {\n      const response = createFarmRequestBodyErrorResponse(error);\n      if (response) return response;\n      if (error instanceof SyntaxError) {\n        return Response.json({ error: \"Invalid workflow request body.\" }, { status: 400 });\n      }\n      throw error;\n    }\n    const module = await options.loadModule(workflow);\n    const result = await runFarmWorkflowModule(module, {\n      id: workflow.id,\n      name: workflow.id,\n      payload,\n      request,\n      scheduledTime: readScheduledTime(payload),\n    });\n\n    return Response.json({\n      id: workflow.id,\n      ok: true,\n      result: result ?? null,\n    });\n  };\n}\n\nexport async function runFarmWorkflowModule(\n  module: Record<string, any>,\n  context: {\n    id: string;\n    name?: string;\n    payload?: unknown;\n    scheduledTime?: number | string;\n    request?: Request;\n    event?: unknown;\n    env?: Record<string, string | undefined>;\n  },\n): Promise<unknown> {\n  const definition = resolveWorkflowDefinition(module);\n  if (!definition) {\n    throw new Error(`Farm workflow \"${context.id}\" does not export a workflow definition.`);\n  }\n\n  return await definition.run({\n    id: context.id,\n    name: context.name || context.id,\n    payload: context.payload,\n    scheduledTime: context.scheduledTime,\n    request: context.request,\n    event: context.event,\n    env: context.env || process.env,\n    data: new Map<string, unknown>(),\n    log: console,\n  });\n}\n\nexport async function prepareFarmWorkflowsForNitro(config: {\n  root?: string;\n  distDir?: string;\n  workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean;\n  server?: FarmServerConfig | ResolvedFarmServerConfig;\n}): Promise<PreparedFarmWorkflows> {\n  const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n    ? config.workflows\n    : resolveWorkflowsConfig(config.workflows);\n  const root = config.root || process.cwd();\n  const distDir = config.distDir || \".farm\";\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const generatedDir = path.join(root, distDir, \".nitro\", \"farm-workflows\");\n  const workflows = await discoverFarmWorkflows({\n    root,\n    workflows: workflowConfig,\n  });\n\n  if (workflows.length === 0) {\n    await fs.rm(generatedDir, { recursive: true, force: true });\n    return {\n      workflows,\n      tasks: {},\n      scheduledTasks: {},\n    };\n  }\n\n  await fs.rm(generatedDir, { recursive: true, force: true });\n  await fs.mkdir(generatedDir, { recursive: true });\n\n  const tasks: PreparedFarmWorkflows[\"tasks\"] = {};\n  const scheduledTasks = createScheduledTasks(workflows);\n\n  const wrapperNames = resolveWorkflowWrapperFileNames(workflows.map((workflow) => workflow.id));\n  for (const workflow of workflows) {\n    const wrapperPath = toPosixPath(\n      path.join(generatedDir, `${wrapperNames.get(workflow.id)}.mjs`),\n    );\n    await fs.writeFile(wrapperPath, createNitroTaskWrapper(workflow), \"utf8\");\n    tasks[workflow.id] = {\n      handler: wrapperPath,\n      description: workflow.description || `Farm workflow ${workflow.id}`,\n    };\n  }\n\n  const handlerPath = toPosixPath(path.join(generatedDir, \"http-handler.mjs\"));\n  await fs.writeFile(\n    handlerPath,\n    createNitroWorkflowHTTPHandler(\n      workflowConfig,\n      workflows,\n      resolveFarmServerConfig(config.server),\n    ),\n    \"utf8\",\n  );\n\n  const manifestPath = path.join(generatedDir, \"manifest.json\");\n  await fs.writeFile(\n    manifestPath,\n    JSON.stringify(\n      {\n        route: workflowConfig.route,\n        secretEnv: workflowConfig.secretEnv,\n        trigger: {\n          method: \"GET\",\n          authorization: `Bearer $${workflowConfig.secretEnv}`,\n        },\n        workflows: workflows.map(toWorkflowMetadata),\n      },\n      null,\n      2,\n    ),\n    \"utf8\",\n  );\n\n  return {\n    workflows,\n    tasks,\n    scheduledTasks,\n    handlerPath,\n    manifestPath,\n  };\n}\n\nexport function createFarmWorkflowVercelCrons(\n  workflows: FarmDiscoveredWorkflow[],\n): Array<{ path: string; schedule: string }> {\n  return workflows.flatMap((workflow) =>\n    workflow.schedule.map((schedule) => ({\n      path: workflow.routePath,\n      schedule,\n    })),\n  );\n}\n\nexport function applyFarmWorkflowVercelCrons(\n  vercelConfig: Record<string, any>,\n  workflows: FarmDiscoveredWorkflow[],\n): Record<string, any> {\n  const crons = createFarmWorkflowVercelCrons(workflows);\n  if (crons.length === 0) return vercelConfig;\n\n  const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n  const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n  const nextCrons = [...existingCrons];\n  for (const cron of crons) {\n    const key = `${cron.path}:${cron.schedule}`;\n    if (seen.has(key)) continue;\n    seen.add(key);\n    nextCrons.push(cron);\n  }\n  return {\n    ...vercelConfig,\n    crons: nextCrons,\n  };\n}\n\nfunction isResolvedWorkflowConfig(value: unknown): value is FarmWorkflowsResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"dirs\" in value &&\n    Array.isArray((value as FarmWorkflowsResolvedConfig).dirs) &&\n    typeof (value as FarmWorkflowsResolvedConfig).route === \"string\"\n  );\n}\n\nfunction normalizeWorkflowDirs(options: FarmWorkflowsUserConfig): string[] {\n  const rawDirs =\n    options.dirs ||\n    (Array.isArray(options.dir) ? options.dir : options.dir ? [options.dir] : undefined);\n  const dirs = rawDirs && rawDirs.length > 0 ? rawDirs : DEFAULT_FARM_WORKFLOW_DIRS;\n  return [...new Set(dirs.map(normalizeWorkflowDir).filter(Boolean))];\n}\n\nfunction normalizeWorkflowDir(value: string): string {\n  const dir = value.trim();\n  if (!dir) return \"\";\n  return isAbsolutePath(dir) ? normalizePath(dir) : trimSlashes(dir);\n}\n\nfunction normalizeWorkflowRoute(route: string): string {\n  const trimmed = route.trim();\n  if (!trimmed || trimmed === \"/\") return DEFAULT_FARM_WORKFLOW_ROUTE;\n  const normalized = `/${trimSlashes(trimmed)}`;\n  validateConfigRouteSource(normalized, \"workflows.route\");\n  return normalized;\n}\n\nfunction normalizeWorkflowId(id: string): string {\n  const normalized = id\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\.(tsx?|jsx?|mjs|cjs)$/, \"\")\n    .replace(/\\/index$/, \"\")\n    .replace(/[^a-zA-Z0-9._/-]+/g, \"-\")\n    .replace(/^\\/+|\\/+$/g, \"\")\n    .replace(/\\/+/g, \"/\");\n  return normalized || \"workflow\";\n}\n\nfunction normalizeSchedule(schedule: FarmWorkflowSchedule | undefined): string[] {\n  if (!schedule) return [];\n  return (Array.isArray(schedule) ? schedule : [schedule])\n    .map((value) => value.trim())\n    .filter(Boolean);\n}\n\nfunction resolveWorkflowDefinition(\n  module: Record<string, any>,\n): FarmWorkflowDefinition | FarmCronDefinition | null {\n  const candidates = [module.default, module.workflow, module.cron, module.task, module.job];\n  for (const candidate of candidates) {\n    if (candidate && typeof candidate === \"object\" && typeof candidate.run === \"function\") {\n      return candidate as FarmWorkflowDefinition;\n    }\n  }\n  return null;\n}\n\nasync function findWorkflowFiles(root: string, dirs: string[]): Promise<string[]> {\n  const path = await import(\"path\");\n  const files: string[] = [];\n\n  for (const dir of dirs) {\n    const absoluteDir = path.isAbsolute(dir) ? dir : path.join(root, dir);\n    if (!(await pathExists(absoluteDir))) continue;\n    await walkWorkflowDir(absoluteDir, files);\n  }\n\n  return files.sort();\n}\n\nasync function walkWorkflowDir(dir: string, files: string[]): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const entries = await fs.readdir(dir, { withFileTypes: true });\n  for (const entry of entries) {\n    const filePath = path.join(dir, entry.name);\n    if (entry.isDirectory()) {\n      if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n      await walkWorkflowDir(filePath, files);\n      continue;\n    }\n    if (isWorkflowFile(entry.name)) {\n      files.push(filePath);\n    }\n  }\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n  const fs = await import(\"fs/promises\");\n  return fs\n    .access(filePath)\n    .then(() => true)\n    .catch(() => false);\n}\n\nfunction isWorkflowFile(fileName: string): boolean {\n  return /\\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(fileName) && !/\\.d\\.[cm]?ts$/.test(fileName);\n}\n\nasync function loadWorkflowModule(filePath: string, root: string): Promise<Record<string, any>> {\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const { pathToFileURL } = await import(\"url\");\n  const { build } = await import(\"esbuild\");\n  const outDir = path.join(root, \".farm\", \".workflow-loader\");\n  await fs.mkdir(outDir, { recursive: true });\n  const outfile = path.join(\n    outDir,\n    `workflow-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n  );\n\n  await build({\n    absWorkingDir: root,\n    entryPoints: [filePath],\n    outfile,\n    bundle: true,\n    format: \"esm\",\n    platform: \"node\",\n    target: `node${process.versions.node.split(\".\")[0]}`,\n    packages: \"external\",\n    external: [\"@farm.js/core\", \"@farm.js/core/*\", \"nitro\", \"nitro/*\"],\n    jsx: \"automatic\",\n    logLevel: \"silent\",\n    sourcemap: \"inline\",\n  });\n\n  try {\n    return await import(/* @vite-ignore */ `${pathToFileURL(outfile).href}?t=${Date.now()}`);\n  } finally {\n    await fs.unlink(outfile).catch(() => undefined);\n  }\n}\n\nfunction workflowIdFromFile(root: string, dirs: string[], filePath: string): string {\n  for (const dir of dirs) {\n    const scanRoot = isAbsolutePath(dir) ? dir : resolvePath(root, dir);\n    const candidate = relativeFilePath(scanRoot, filePath);\n    if (candidate && candidate !== \"..\" && !candidate.startsWith(`..${pathSeparator}`)) {\n      return normalizeWorkflowId(candidate);\n    }\n  }\n\n  return normalizeWorkflowId(relativeFilePath(root, filePath));\n}\n\nfunction createScheduledTasks(\n  workflows: FarmDiscoveredWorkflow[],\n): Record<string, string | string[]> {\n  const scheduleMap = new Map<string, string[]>();\n  for (const workflow of workflows) {\n    for (const schedule of workflow.schedule) {\n      const taskIds = scheduleMap.get(schedule) || [];\n      taskIds.push(workflow.id);\n      scheduleMap.set(schedule, taskIds);\n    }\n  }\n\n  return Object.fromEntries(\n    [...scheduleMap.entries()].map(([schedule, taskIds]) => [\n      schedule,\n      taskIds.length === 1 ? taskIds[0] : taskIds,\n    ]),\n  );\n}\n\nfunction createNitroTaskWrapper(workflow: FarmDiscoveredWorkflow): string {\n  const normalizedPath = workflow.filePath.replace(/\\\\/g, \"/\");\n  return `\nimport { defineTask } from \"nitro/runtime\";\nimport { runFarmWorkflowModule } from \"@farm.js/core/workflows\";\nimport * as workflowModule from ${JSON.stringify(normalizedPath)};\n\nexport default defineTask({\n  meta: {\n    description: ${JSON.stringify(workflow.description || `Farm workflow ${workflow.id}`)}\n  },\n  async run(event) {\n    const payload = event?.payload || {};\n    const env = event?.context?.cloudflare?.env || event?.context?.env || process.env;\n    return await runFarmWorkflowModule(workflowModule, {\n      id: ${JSON.stringify(workflow.id)},\n      name: event?.name || ${JSON.stringify(workflow.id)},\n      payload,\n      scheduledTime: payload.scheduledTime,\n      request: event?.context?.request,\n      event,\n      env\n    });\n  }\n});\n`.trim();\n}\n\nfunction createNitroWorkflowHTTPHandler(\n  config: FarmWorkflowsResolvedConfig,\n  workflows: FarmDiscoveredWorkflow[],\n  server: ResolvedFarmServerConfig,\n): string {\n  return `\nimport { H3 } from \"h3\";\nimport { runTask } from \"nitro/runtime\";\nimport {\n  createFarmRequestBodyErrorResponse,\n  farmSecretsMatch,\n  readFarmRequestBody,\n  searchParamsToObject\n} from \"@farm.js/core/internal/production-runtime\";\n\nconst route = ${JSON.stringify(config.route)};\nconst secretEnv = ${JSON.stringify(config.secretEnv)};\nconst inlineSecret = ${JSON.stringify(config.secret || \"\")};\nconst allowUnsecured = ${JSON.stringify(config.allowUnsecured === true)};\nconst bodySizeLimit = ${JSON.stringify(server.bodySizeLimit)};\nconst workflows = ${JSON.stringify(workflows.map(toWorkflowMetadata))};\nconst workflowIds = new Set(workflows.map((workflow) => workflow.id));\n\nfunction json(value, status = 200) {\n  return new Response(JSON.stringify(value), {\n    status,\n    headers: { \"content-type\": \"application/json\" }\n  });\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction getHeader(event, name) {\n  return event.req.headers.get(name);\n}\n\nfunction getSecret() {\n  // Match the dev-path verifyWorkflowSecret's resolution (readFarmEnvironmentValue):\n  // runtime bindings on globalThis.__env__ first, then process.env. Reading\n  // process.env alone misses a Cloudflare Workers secret, so a correctly\n  // configured deployment would see no secret and reject every request with 401.\n  const runtimeBindings = globalThis.__env__;\n  const runtimeSecret =\n    runtimeBindings && typeof runtimeBindings === \"object\" ? runtimeBindings[secretEnv] : undefined;\n  const resolved =\n    typeof runtimeSecret === \"string\"\n      ? runtimeSecret\n      : typeof process !== \"undefined\"\n        ? process.env?.[secretEnv]\n        : undefined;\n  return inlineSecret || resolved || \"\";\n}\n\nfunction verifySecret(event) {\n  const secret = getSecret();\n  if (!secret) {\n    if (allowUnsecured) return null;\n    return json({ error: ${JSON.stringify(MISSING_FARM_WORKFLOW_SECRET_ERROR)} }, 401);\n  }\n  const authorization = getHeader(event, \"authorization\") || \"\";\n  const headerSecret = getHeader(event, \"x-farm-workflow-secret\") || \"\";\n  const bearer = authorization.match(/^Bearer\\\\s+(.+)$/i)?.[1] || \"\";\n  if (farmSecretsMatch(headerSecret, secret) || farmSecretsMatch(bearer, secret)) return null;\n  return json({ error: \"Unauthorized workflow request.\" }, 401);\n}\n\nasync function readPayload(event) {\n  if (event.req.method === \"GET\" || event.req.method === \"HEAD\") {\n    return searchParamsToObject(event.url.searchParams);\n  }\n  const bytes = await readFarmRequestBody(event.req, bodySizeLimit);\n  const text = new TextDecoder().decode(bytes);\n  if (!text) return {};\n  const contentType = (getHeader(event, \"content-type\") || \"\").split(\";\", 1)[0].trim().toLowerCase();\n  if (\n    contentType === \"application/json\" ||\n    (contentType.startsWith(\"application/\") && contentType.endsWith(\"+json\"))\n  ) {\n    return JSON.parse(text);\n  }\n  return { text };\n}\n\nexport default new H3()\n  .get(route, (event) => {\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n    return { workflows };\n  })\n  .all(route + \"/:id\", async (event) => {\n    const id = decodeRouteSegment(event.context.params?.id || \"\");\n\n    // Verify the secret before consulting the workflow id map so the\n    // existing-vs-missing distinction is not disclosed to callers without\n    // the secret (a 401 for unknown ids would otherwise become a 404 oracle).\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n\n    if (!workflowIds.has(id)) {\n      return json({ error: \"Workflow \" + id + \" was not found.\" }, 404);\n    }\n\n    let payload;\n    try {\n      payload = await readPayload(event);\n    } catch (error) {\n      const response = createFarmRequestBodyErrorResponse(error);\n      if (response) return response;\n      if (error instanceof SyntaxError) return json({ error: \"Invalid workflow request body.\" }, 400);\n      throw error;\n    }\n    const result = await runTask(id, {\n      payload,\n      context: {\n        source: \"http\",\n        request: event.req,\n        route,\n        url: event.url.href,\n        method: event.req.method\n      }\n    });\n    return {\n      id,\n      ok: true,\n      result: result ?? null\n    };\n  });\n`.trim();\n}\n\nfunction toWorkflowMetadata(workflow: FarmDiscoveredWorkflow) {\n  return {\n    id: workflow.id,\n    description: workflow.description || null,\n    schedule: workflow.schedule,\n    timezone: workflow.timezone || null,\n    path: workflow.routePath,\n  };\n}\n\nasync function readWorkflowPayload(request: Request, bodySizeLimit: number): Promise<unknown> {\n  const url = new URL(request.url);\n  if (request.method === \"GET\" || request.method === \"HEAD\") {\n    return searchParamsToObject(url.searchParams);\n  }\n\n  const bytes = await readFarmRequestBody(request, bodySizeLimit);\n  const text = new TextDecoder().decode(bytes);\n  if (!text) return {};\n  const contentType = (request.headers.get(\"content-type\") || \"\")\n    .split(\";\", 1)[0]\n    .trim()\n    .toLowerCase();\n  if (\n    contentType === \"application/json\" ||\n    (contentType.startsWith(\"application/\") && contentType.endsWith(\"+json\"))\n  ) {\n    return JSON.parse(text);\n  }\n\n  return { text };\n}\n\nfunction readScheduledTime(payload: unknown): number | string | undefined {\n  return payload && typeof payload === \"object\" && \"scheduledTime\" in payload\n    ? (payload as { scheduledTime?: number | string }).scheduledTime\n    : undefined;\n}\n\nfunction verifyWorkflowSecret(\n  request: Request,\n  config: FarmWorkflowsResolvedConfig,\n): Response | null {\n  const secret = config.secret || readFarmEnvironmentValue(config.secretEnv) || \"\";\n  if (!secret) {\n    // No secret configured. Local development stays convenient, but a deployed\n    // runtime must not expose a route that lists and executes workflows to\n    // anonymous callers. Opt back in explicitly with .\n    if (config.allowUnsecured === true || !isFarmDeployedRuntime()) return null;\n    return Response.json(\n      {\n        error: MISSING_FARM_WORKFLOW_SECRET_ERROR,\n      },\n      { status: 401 },\n    );\n  }\n\n  const authorization = request.headers.get(\"authorization\") || \"\";\n  const bearer = authorization.match(/^Bearer\\s+(.+)$/i)?.[1] || \"\";\n  const headerSecret = request.headers.get(\"x-farm-workflow-secret\") || \"\";\n  if (farmSecretsMatch(bearer, secret) || farmSecretsMatch(headerSecret, secret)) return null;\n\n  return Response.json({ error: \"Unauthorized workflow request.\" }, { status: 401 });\n}\n\nfunction joinRoute(...parts: string[]): string {\n  return `/${parts\n    .map((part) => trimSlashes(part))\n    .filter(Boolean)\n    .join(\"/\")}`;\n}\n\nfunction trimSlashes(value: string): string {\n  return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\n/**\n * Wrapper file names for a set of workflow ids.\n *\n * `safeFileName` is not injective: it maps `a/b` and `a-b` onto the same string,\n * and macOS and Windows additionally fold `Daily` onto `daily` on their default\n * case-insensitive filesystems. Two workflows would then share one generated\n * wrapper and both run whichever was written last. Only ids that actually\n * collide are disambiguated, so ordinary ids keep a readable wrapper; every id\n * in a colliding group gets a digest of the exact id appended, which keeps the\n * result independent of discovery order.\n */\nfunction resolveWorkflowWrapperFileNames(ids: readonly string[]): Map<string, string> {\n  const groups = new Map<string, number>();\n  for (const id of ids) {\n    const key = safeFileName(id).toLowerCase();\n    groups.set(key, (groups.get(key) ?? 0) + 1);\n  }\n\n  const resolved = new Map<string, string>();\n  const claimed = new Map<string, string>();\n  for (const id of ids) {\n    const base = safeFileName(id);\n    const key = base.toLowerCase();\n    const fileName = (groups.get(key) ?? 0) > 1 ? `${key}-${workflowIdFingerprint(id)}` : base;\n    const claimedBy = claimed.get(fileName.toLowerCase());\n    if (claimedBy !== undefined) {\n      throw new Error(\n        `Farm workflows ${JSON.stringify(claimedBy)} and ${JSON.stringify(id)} generate the same wrapper file ${JSON.stringify(`${fileName}.mjs`)}. Rename one of them.`,\n      );\n    }\n    claimed.set(fileName.toLowerCase(), id);\n    resolved.set(id, fileName);\n  }\n  return resolved;\n}\n\n/**\n * FNV-1a. This module is bundled into server runtimes that do not provide\n * node:crypto, and the digest only needs to separate file names.\n */\nfunction workflowIdFingerprint(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < value.length; index += 1) {\n    hash ^= value.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction safeFileName(value: string): string {\n  return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"workflow\";\n}\n\nfunction relativePath(root: string, filePath: string): string {\n  return filePath.replace(/\\\\/g, \"/\").replace(`${root.replace(/\\\\/g, \"/\")}/`, \"\");\n}\n","export interface EnvSchema<TOutput = unknown> {\n  parse(value: unknown): TOutput;\n}\n\nexport type EnvParser<TOutput = unknown> =\n  | EnvSchema<TOutput>\n  | ((value: string | undefined, context: { key: string; scope: \"server\" | \"public\" }) => TOutput);\n\nexport type EnvShape = Record<string, EnvParser<any>>;\n\nexport type InferEnvParser<TParser> =\n  TParser extends EnvSchema<infer TOutput>\n    ? TOutput\n    : TParser extends (value: string | undefined, context: any) => infer TOutput\n      ? TOutput\n      : never;\n\nexport type InferEnvShape<TShape> = TShape extends EnvShape\n  ? { [K in keyof TShape]: InferEnvParser<TShape[K]> }\n  : {};\n\nexport interface FarmEnvConfig<\n  TServer extends EnvShape = EnvShape,\n  TPublic extends EnvShape = EnvShape,\n> {\n  server?: TServer;\n  public?: TPublic;\n}\n\nexport interface ResolvedFarmEnv<\n  TServer extends Record<string, any> = Record<string, unknown>,\n  TPublic extends Record<string, any> = Record<string, unknown>,\n> {\n  server: TServer;\n  public: TPublic;\n}\n\nexport type InferEnv<TConfig> =\n  TConfig extends FarmEnvConfig<infer TServer, infer TPublic>\n    ? ResolvedFarmEnv<InferEnvShape<TServer>, InferEnvShape<TPublic>>\n    : ResolvedFarmEnv;\n\n/**\n * Augmented by generated src/farm.d.ts for project-specific autocomplete.\n */\nexport interface FarmEnvTypes {}\n\nexport type FarmServerEnv = FarmEnvTypes extends { server: infer TServer }\n  ? TServer extends Record<string, any>\n    ? TServer\n    : Record<string, unknown>\n  : Record<string, unknown>;\n\nexport type FarmPublicEnv = FarmEnvTypes extends { public: infer TPublic }\n  ? TPublic extends Record<string, any>\n    ? TPublic\n    : Record<string, unknown>\n  : Record<string, unknown>;\n\nexport type FarmTypedEnv = ResolvedFarmEnv<FarmServerEnv, FarmPublicEnv>;\n\ndeclare const __FARM_PUBLIC_ENV__: Record<string, unknown> | undefined;\ndeclare const __FARM_ENV__: ResolvedFarmEnv | undefined;\n\nconst FARM_ENV_SYMBOL = Symbol.for(\"farm.env\");\nconst farmEnvGlobal = globalThis as typeof globalThis & {\n  [FARM_ENV_SYMBOL]?: ResolvedFarmEnv;\n};\nlet currentEnv: ResolvedFarmEnv = getInitialEnv();\n\nexport function resolveEnv<TConfig extends FarmEnvConfig<any, any> | undefined>(\n  config: TConfig,\n  source: Record<string, string | undefined> = getProcessEnv(),\n): InferEnv<NonNullable<TConfig>> {\n  const resolved = {\n    server: resolveEnvScope(config?.server, source, \"server\"),\n    public: resolveEnvScope(config?.public, source, \"public\"),\n  } as InferEnv<NonNullable<TConfig>>;\n\n  return resolved;\n}\n\nexport function setEnv(env: ResolvedFarmEnv): void {\n  currentEnv = normalizeResolvedEnv(env);\n  if (typeof window === \"undefined\") {\n    farmEnvGlobal[FARM_ENV_SYMBOL] = currentEnv;\n  }\n}\n\nexport function getResolvedEnv<TEnv extends ResolvedFarmEnv = FarmTypedEnv>(): TEnv {\n  return getCurrentEnv() as TEnv;\n}\n\nexport function getEnv<TServer extends Record<string, any> = FarmServerEnv>(): TServer;\nexport function getEnv<TKey extends Extract<keyof FarmServerEnv, string>>(\n  key: TKey,\n): FarmServerEnv[TKey];\nexport function getEnv(key?: string): unknown {\n  assertServerEnvAccess();\n  if (key === undefined) {\n    return getCurrentEnv().server;\n  }\n\n  return getCurrentEnv().server[key];\n}\n\nexport function getPublicEnv<TPublic extends Record<string, any> = FarmPublicEnv>(): TPublic;\nexport function getPublicEnv<TKey extends Extract<keyof FarmPublicEnv, string>>(\n  key: TKey,\n): FarmPublicEnv[TKey];\nexport function getPublicEnv(key?: string): unknown {\n  if (key === undefined) {\n    return getCurrentEnv().public;\n  }\n\n  return getCurrentEnv().public[key];\n}\n\nexport const env = createEnvProxy(\"server\") as FarmServerEnv;\nexport const serverEnv = env;\nexport const publicEnv = createEnvProxy(\"public\") as FarmPublicEnv;\n\nfunction resolveEnvScope(\n  shape: EnvShape | undefined,\n  source: Record<string, string | undefined>,\n  scope: \"server\" | \"public\",\n): Record<string, unknown> {\n  if (!shape) {\n    return {};\n  }\n\n  const resolved: Record<string, unknown> = {};\n\n  for (const [key, parser] of Object.entries(shape)) {\n    try {\n      resolved[key] = parseEnvValue(parser, source[key], key, scope);\n    } catch (error) {\n      const message = error instanceof Error ? error.message : String(error);\n      throw new Error(`Invalid ${scope} env \"${key}\": ${message}`);\n    }\n  }\n\n  return resolved;\n}\n\nfunction parseEnvValue(\n  parser: EnvParser<any>,\n  value: string | undefined,\n  key: string,\n  scope: \"server\" | \"public\",\n): unknown {\n  if (typeof parser === \"function\") {\n    return parser(value, { key, scope });\n  }\n\n  if (parser && typeof parser.parse === \"function\") {\n    return parser.parse(value);\n  }\n\n  throw new Error(\"expected a parser function or schema with parse()\");\n}\n\nfunction createEnvProxy(scope: \"server\" | \"public\"): Record<string, unknown> {\n  return new Proxy(\n    {},\n    {\n      get(_target, property) {\n        if (typeof property === \"symbol\") {\n          return undefined;\n        }\n\n        const env = getEnvScope(scope);\n        return env[property];\n      },\n      ownKeys() {\n        return Reflect.ownKeys(getEnvScope(scope));\n      },\n      getOwnPropertyDescriptor(_target, property) {\n        const env = getEnvScope(scope);\n        if (!(property in env)) {\n          return undefined;\n        }\n\n        return {\n          enumerable: true,\n          configurable: true,\n          value: env[property as keyof typeof env],\n        };\n      },\n      has(_target, property) {\n        return property in getEnvScope(scope);\n      },\n    },\n  );\n}\n\nfunction getEnvScope(scope: \"server\" | \"public\"): Record<string, unknown> {\n  if (scope === \"server\") {\n    assertServerEnvAccess();\n  }\n\n  return getCurrentEnv()[scope] || {};\n}\n\nfunction assertServerEnvAccess(): void {\n  if (typeof window !== \"undefined\") {\n    throw new Error(\"Farm server env is not available in the browser. Use publicEnv.\");\n  }\n}\n\nfunction getInitialEnv(): ResolvedFarmEnv {\n  const injectedEnv = getInjectedEnv();\n  if (injectedEnv) {\n    return injectedEnv;\n  }\n\n  if (typeof window === \"undefined\" && farmEnvGlobal[FARM_ENV_SYMBOL]) {\n    return normalizeResolvedEnv(farmEnvGlobal[FARM_ENV_SYMBOL]);\n  }\n\n  return {\n    server: {},\n    public: getInjectedPublicEnv(),\n  };\n}\n\nfunction getCurrentEnv(): ResolvedFarmEnv {\n  if (typeof window === \"undefined\" && farmEnvGlobal[FARM_ENV_SYMBOL]) {\n    return farmEnvGlobal[FARM_ENV_SYMBOL];\n  }\n\n  return currentEnv;\n}\n\nfunction getInjectedEnv(): ResolvedFarmEnv | null {\n  try {\n    if (typeof __FARM_ENV__ !== \"undefined\" && __FARM_ENV__) {\n      return normalizeResolvedEnv(__FARM_ENV__);\n    }\n  } catch {\n    // The compile-time global is only defined in Farm server bundles.\n  }\n\n  return null;\n}\n\nfunction getInjectedPublicEnv(): Record<string, unknown> {\n  try {\n    if (typeof __FARM_PUBLIC_ENV__ !== \"undefined\" && __FARM_PUBLIC_ENV__) {\n      return __FARM_PUBLIC_ENV__;\n    }\n  } catch {\n    // The compile-time global is only defined in Farm browser bundles.\n  }\n\n  return {};\n}\n\nfunction normalizeResolvedEnv(env: ResolvedFarmEnv): ResolvedFarmEnv {\n  return {\n    server: isRecord(env.server) ? env.server : {},\n    public: isRecord(env.public) ? env.public : {},\n  };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction getProcessEnv(): Record<string, string | undefined> {\n  if (typeof process !== \"undefined\" && process.env) {\n    return process.env;\n  }\n\n  return {};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { subscribeFarmCacheInvalidation, subscribeFarmCacheTask } from \"./cache-invalidation\";\nimport {\n  getRequestSourceOrigin,\n  matchesAllowedOrigin,\n  matchesHostHeader,\n  normalizeAllowedOriginPattern,\n} from \"./request-origin\";\nimport { serializeServerFnFailure, type SerializedServerFnFailure } from \"./server-fn-error\";\nimport { parseBodySizeLimit } from \"./server-http\";\n\nconst SERVER_ACTION_ALLOWED_ORIGINS_LABEL = \"serverActions.allowedOrigins\";\n\nexport const DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT = 1_000_000;\n\nexport interface FarmServerActionsConfig {\n  /** Additional trusted origins or host patterns, such as https://app.example.com. */\n  allowedOrigins?: readonly string[];\n  /** Maximum encoded request body size in bytes or as a size string such as \"1mb\". */\n  bodySizeLimit?: number | string;\n}\n\nexport interface ResolvedFarmServerActionsConfig {\n  allowedOrigins: readonly string[];\n  bodySizeLimit: number;\n}\n\nexport type ServerActionRequestKind = \"javascript\" | \"form\";\n\nexport interface PreparedServerActionRequest {\n  body: string | FormData;\n  contentType: string;\n}\n\nexport type SanitizedServerActionError =\n  | {\n      name: \"ServerActionError\";\n      message: \"Server function failed\";\n    }\n  | SerializedServerFnFailure;\n\ntype ServerActionRequestErrorCode =\n  | \"BODY_TOO_LARGE\"\n  | \"INVALID_ACTION_ID\"\n  | \"INVALID_BODY\"\n  | \"INVALID_CONTENT_LENGTH\"\n  | \"INVALID_METHOD\"\n  | \"INVALID_ORIGIN\"\n  | \"MISSING_ORIGIN\"\n  | \"UNSUPPORTED_CONTENT_TYPE\";\n\nexport class ServerActionRequestError extends Error {\n  readonly code: ServerActionRequestErrorCode;\n  readonly status: number;\n\n  constructor(code: ServerActionRequestErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"ServerActionRequestError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\ntype ServerActionExecutionContext = {\n  request: Request;\n  signal: AbortSignal;\n  invalidations: Set<string>;\n  cacheTasks: Set<Promise<void>>;\n};\n\nconst SERVER_ACTION_STORAGE_KEY = Symbol.for(\"farm.serverActionStorage\");\nconst FALLBACK_ABORT_CONTROLLER_KEY = Symbol.for(\"farm.serverActionFallbackAbortController\");\nconst FORM_ACTION_CONTENT_TYPES = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n]);\nconst JAVASCRIPT_ACTION_CONTENT_TYPES = new Set([\n  \"application/octet-stream\",\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\ntype GlobalWithServerActionStorage = typeof globalThis & {\n  [SERVER_ACTION_STORAGE_KEY]?: AsyncLocalStorage<ServerActionExecutionContext>;\n  [FALLBACK_ABORT_CONTROLLER_KEY]?: AbortController;\n};\n\nexport function resolveServerActionsConfig(\n  config: FarmServerActionsConfig | undefined,\n): ResolvedFarmServerActionsConfig {\n  const allowedOrigins = (config?.allowedOrigins ?? []).map((value) =>\n    normalizeAllowedOriginPattern(value, SERVER_ACTION_ALLOWED_ORIGINS_LABEL),\n  );\n  const bodySizeLimit = parseBodySizeLimit(\n    config?.bodySizeLimit ?? DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT,\n    \"serverActions.bodySizeLimit\",\n  );\n\n  return Object.freeze({\n    allowedOrigins: Object.freeze(allowedOrigins),\n    bodySizeLimit,\n  });\n}\n\nexport function validateServerActionRequest(\n  request: Request,\n  config: ResolvedFarmServerActionsConfig,\n): void {\n  if (request.method.toUpperCase() !== \"POST\") {\n    throw new ServerActionRequestError(\n      \"INVALID_METHOD\",\n      405,\n      \"Server actions only accept POST requests\",\n    );\n  }\n\n  const requestUrl = new URL(request.url);\n  const sourceOrigin = resolveSourceOrigin(request);\n  const fetchSite = request.headers.get(\"sec-fetch-site\")?.trim().toLowerCase();\n\n  if (!sourceOrigin) {\n    if (fetchSite !== \"same-origin\") {\n      throw new ServerActionRequestError(\n        \"MISSING_ORIGIN\",\n        403,\n        \"Server action request is missing same-origin metadata\",\n      );\n    }\n    return;\n  }\n\n  const matchesRequest =\n    sourceOrigin === requestUrl.origin || matchesHostHeader(sourceOrigin, request);\n  const matchesConfiguredOrigin = config.allowedOrigins.some((pattern) =>\n    matchesAllowedOrigin(sourceOrigin, pattern),\n  );\n\n  if (!matchesRequest && !matchesConfiguredOrigin) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      \"Server action origin does not match the request origin\",\n    );\n  }\n\n  if (fetchSite === \"cross-site\" && !matchesConfiguredOrigin) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      \"Cross-site server action request was rejected\",\n    );\n  }\n}\n\nexport async function prepareServerActionRequest(\n  request: Request,\n  config: ResolvedFarmServerActionsConfig,\n  kind: ServerActionRequestKind,\n  actionId?: string | null,\n): Promise<PreparedServerActionRequest> {\n  validateServerActionRequest(request, config);\n\n  if (kind === \"javascript\") {\n    validateActionId(actionId);\n  }\n\n  const contentType = getSupportedContentType(request, kind);\n  const bytes = await readBodyWithLimit(request, config.bodySizeLimit);\n\n  if (kind === \"form\" || contentType === \"multipart/form-data\") {\n    return {\n      body: await parseFormData(request, bytes),\n      contentType,\n    };\n  }\n\n  return {\n    body: new TextDecoder().decode(bytes),\n    contentType,\n  };\n}\n\nexport function createServerActionRequestErrorResponse(error: unknown): Response | null {\n  if (!(error instanceof ServerActionRequestError)) {\n    return null;\n  }\n\n  const headers = new Headers({\n    \"cache-control\": \"no-store\",\n    \"content-type\": \"text/plain; charset=utf-8\",\n    \"x-content-type-options\": \"nosniff\",\n  });\n  if (error.status === 405) {\n    headers.set(\"allow\", \"POST\");\n  }\n\n  return new Response(getPublicErrorMessage(error.status), {\n    status: error.status,\n    headers,\n  });\n}\n\nexport function sanitizeServerActionError(error: unknown): SanitizedServerActionError {\n  const declaredFailure = serializeServerFnFailure(error);\n  if (declaredFailure) return declaredFailure;\n\n  return {\n    name: \"ServerActionError\",\n    message: \"Server function failed\",\n  };\n}\n\nexport async function runWithServerActionRequest<T>(\n  request: Request,\n  callback: () => T | Promise<T>,\n): Promise<T> {\n  throwIfAborted(request.signal);\n  const context: ServerActionExecutionContext = {\n    request,\n    signal: request.signal,\n    invalidations: new Set(),\n    cacheTasks: new Set(),\n  };\n\n  return getServerActionStorage().run(context, async () => {\n    try {\n      const result = await callback();\n      await Promise.all(context.cacheTasks);\n      return result;\n    } catch (error) {\n      await Promise.allSettled(context.cacheTasks);\n      throw error;\n    }\n  });\n}\n\nexport function getServerActionExecutionContext(): ServerActionExecutionContext | undefined {\n  return getServerActionStorage().getStore();\n}\n\nexport function getServerActionSignal(): AbortSignal {\n  return getServerActionExecutionContext()?.signal ?? getFallbackAbortController().signal;\n}\n\nexport function getServerActionInvalidations(): readonly string[] {\n  return Array.from(getServerActionExecutionContext()?.invalidations ?? []);\n}\n\nsubscribeFarmCacheInvalidation((key) => {\n  getServerActionExecutionContext()?.invalidations.add(key);\n});\n\nsubscribeFarmCacheTask((task) => {\n  getServerActionExecutionContext()?.cacheTasks.add(task);\n});\n\nfunction getServerActionStorage(): AsyncLocalStorage<ServerActionExecutionContext> {\n  const globalState = globalThis as GlobalWithServerActionStorage;\n  if (!globalState[SERVER_ACTION_STORAGE_KEY]) {\n    globalState[SERVER_ACTION_STORAGE_KEY] = new AsyncLocalStorage<ServerActionExecutionContext>();\n  }\n  return globalState[SERVER_ACTION_STORAGE_KEY]!;\n}\n\nfunction getFallbackAbortController(): AbortController {\n  const globalState = globalThis as GlobalWithServerActionStorage;\n  if (!globalState[FALLBACK_ABORT_CONTROLLER_KEY]) {\n    globalState[FALLBACK_ABORT_CONTROLLER_KEY] = new AbortController();\n  }\n  return globalState[FALLBACK_ABORT_CONTROLLER_KEY]!;\n}\n\n/**\n * Adapt the shared origin resolution onto the server-action error contract:\n * an unusable Origin/Referer is a 403 here, while a request that simply\n * carried neither header returns null for the caller to judge.\n */\nfunction resolveSourceOrigin(request: Request): string | null {\n  const result = getRequestSourceOrigin(request);\n\n  if (!result.ok) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      result.reason === \"opaque-origin\"\n        ? \"Opaque origins are not allowed\"\n        : \"Invalid request origin\",\n    );\n  }\n\n  return result.origin;\n}\n\nfunction validateActionId(actionId?: string | null): asserts actionId is string {\n  if (!actionId || actionId.length > 4096 || hasControlCharacters(actionId)) {\n    throw new ServerActionRequestError(\"INVALID_ACTION_ID\", 400, \"Invalid server action id\");\n  }\n}\n\nfunction hasControlCharacters(value: string): boolean {\n  for (let index = 0; index < value.length; index++) {\n    const code = value.charCodeAt(index);\n    if (code <= 31 || code === 127) return true;\n  }\n  return false;\n}\n\nfunction getSupportedContentType(request: Request, kind: ServerActionRequestKind): string {\n  const header = request.headers.get(\"content-type\")?.trim().toLowerCase();\n  const contentType = header?.split(\";\", 1)[0]?.trim() ?? \"\";\n  const supported = kind === \"form\" ? FORM_ACTION_CONTENT_TYPES : JAVASCRIPT_ACTION_CONTENT_TYPES;\n\n  if (!supported.has(contentType)) {\n    throw new ServerActionRequestError(\n      \"UNSUPPORTED_CONTENT_TYPE\",\n      415,\n      \"Unsupported server action content type\",\n    );\n  }\n\n  return contentType;\n}\n\nasync function readBodyWithLimit(request: Request, limit: number): Promise<Uint8Array> {\n  const contentLength = request.headers.get(\"content-length\")?.trim();\n  if (contentLength) {\n    if (!/^\\d+$/.test(contentLength)) {\n      throw new ServerActionRequestError(\n        \"INVALID_CONTENT_LENGTH\",\n        400,\n        \"Invalid content-length header\",\n      );\n    }\n    if (Number(contentLength) > limit) {\n      throw new ServerActionRequestError(\"BODY_TOO_LARGE\", 413, \"Server action body is too large\");\n    }\n  }\n\n  throwIfAborted(request.signal);\n  if (!request.body) return new Uint8Array();\n\n  const reader = request.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  const cancelBodyRead = () => {\n    void reader.cancel(request.signal.reason).catch(() => {});\n  };\n\n  request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n  try {\n    while (true) {\n      throwIfAborted(request.signal);\n      const { done, value } = await reader.read();\n      if (done) break;\n      if (!value) continue;\n\n      total += value.byteLength;\n      if (total > limit) {\n        const error = new ServerActionRequestError(\n          \"BODY_TOO_LARGE\",\n          413,\n          \"Server action body is too large\",\n        );\n        // As with API bodies, a cloned stream may wait for its untouched tee\n        // branch. Cleanup must neither delay rejection nor replace its error.\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } catch (error) {\n    if (request.signal.aborted) throwIfAborted(request.signal);\n    throw error;\n  } finally {\n    request.signal.removeEventListener(\"abort\", cancelBodyRead);\n    reader.releaseLock();\n  }\n\n  throwIfAborted(request.signal);\n  const body = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    body.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return body;\n}\n\nasync function parseFormData(request: Request, bytes: Uint8Array): Promise<FormData> {\n  const body = new ArrayBuffer(bytes.byteLength);\n  new Uint8Array(body).set(bytes);\n  const copy = new Request(request.url, {\n    method: \"POST\",\n    headers: request.headers,\n    body,\n  });\n\n  try {\n    return await copy.formData();\n  } catch {\n    throw new ServerActionRequestError(\"INVALID_BODY\", 400, \"Invalid server action form body\");\n  }\n}\n\nfunction getPublicErrorMessage(status: number): string {\n  switch (status) {\n    case 400:\n      return \"Bad Request\";\n    case 403:\n      return \"Forbidden\";\n    case 405:\n      return \"Method Not Allowed\";\n    case 413:\n      return \"Payload Too Large\";\n    case 415:\n      return \"Unsupported Media Type\";\n    default:\n      return \"Server Action Request Failed\";\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (!signal.aborted) return;\n  if (signal.reason !== undefined) throw signal.reason;\n  throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","export type FarmCacheInvalidationListener = (key: string) => void;\nexport type FarmCacheTaskListener = (task: Promise<void>) => void;\n\nexport const FARM_CACHE_INVALIDATION_HEADER = \"x-farm-cache-invalidations\";\n\ntype FarmCacheInvalidationState = {\n  listeners: Set<FarmCacheInvalidationListener>;\n  taskListeners: Set<FarmCacheTaskListener>;\n};\n\nconst FARM_CACHE_INVALIDATION_STATE = Symbol.for(\"farm.cacheInvalidationState\");\nconst globalState = globalThis as typeof globalThis & {\n  [FARM_CACHE_INVALIDATION_STATE]?: FarmCacheInvalidationState;\n};\n\nfunction getFarmCacheInvalidationState(): FarmCacheInvalidationState {\n  return (globalState[FARM_CACHE_INVALIDATION_STATE] ??= {\n    listeners: new Set(),\n    taskListeners: new Set(),\n  });\n}\n\nfunction warnFarmCacheListenerError(scope: string, error: unknown): void {\n  const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);\n  console.warn(`[farm:cache] ${scope} listener failed: ${detail}`);\n}\n\nexport function notifyFarmCacheInvalidation(key: string): void {\n  if (typeof key !== \"string\" || key.length === 0) return;\n\n  for (const listener of getFarmCacheInvalidationState().listeners) {\n    // Isolate listeners: one throwing observer must not abort the remaining\n    // listeners (or the rest of a multi-key batch in applyFarmCacheInvalidations)\n    // and must not surface as a 500 when invalidation runs inside a request.\n    try {\n      listener(key);\n    } catch (error) {\n      warnFarmCacheListenerError(\"invalidation\", error);\n    }\n  }\n}\n\nexport function notifyFarmCacheTask(task: Promise<void>): void {\n  for (const listener of getFarmCacheInvalidationState().taskListeners) {\n    try {\n      listener(task);\n    } catch (error) {\n      warnFarmCacheListenerError(\"task\", error);\n    }\n  }\n}\n\nexport function applyFarmCacheInvalidations(keys: unknown): void {\n  if (!Array.isArray(keys)) return;\n\n  for (const key of keys) {\n    if (typeof key === \"string\") {\n      notifyFarmCacheInvalidation(key);\n    }\n  }\n}\n\nexport function encodeFarmCacheInvalidations(keys: readonly string[]): string | null {\n  const normalized = Array.from(\n    new Set(keys.filter((key) => typeof key === \"string\" && key.length > 0)),\n  );\n  if (normalized.length === 0) return null;\n  return encodeURIComponent(JSON.stringify(normalized));\n}\n\nexport function decodeFarmCacheInvalidations(value: string | null | undefined): readonly string[] {\n  if (!value) return [];\n\n  try {\n    const parsed = JSON.parse(decodeURIComponent(value));\n    return Array.isArray(parsed)\n      ? Array.from(\n          new Set(parsed.filter((key): key is string => typeof key === \"string\" && key.length > 0)),\n        )\n      : [];\n  } catch {\n    return [];\n  }\n}\n\nexport function subscribeFarmCacheInvalidation(\n  listener: FarmCacheInvalidationListener,\n): () => void {\n  const state = getFarmCacheInvalidationState();\n  state.listeners.add(listener);\n  return () => state.listeners.delete(listener);\n}\n\nexport function subscribeFarmCacheTask(listener: FarmCacheTaskListener): () => void {\n  const state = getFarmCacheInvalidationState();\n  state.taskListeners.add(listener);\n  return () => state.taskListeners.delete(listener);\n}\n","import { existsSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { mkdir, unlink } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\ntype EsbuildTransform = (typeof import(\"esbuild\"))[\"transform\"];\n\nexport type FarmLayerEntry = string;\n\nexport interface ResolvedFarmLayer {\n  /** The value used in `extends`. */\n  source: string;\n  /** Stable name used by the `#layers/<name>` alias. */\n  name: string;\n  /** Absolute layer package or directory root. */\n  root: string;\n  /** Source directory relative to the layer root. */\n  srcDir: string;\n  /** Resolved layer config file when one exists. */\n  configFile?: string;\n}\n\nexport interface FarmSourceRoot {\n  name: string;\n  root: string;\n  srcDir: string;\n  layer: boolean;\n}\n\nexport interface ResolveFarmLayersOptions {\n  root: string;\n  mode: \"development\" | \"production\";\n}\n\nexport interface FarmLayerResolution<TConfig extends Record<string, any>> {\n  config: TConfig & {\n    extends?: readonly FarmLayerEntry[];\n    layers: ResolvedFarmLayer[];\n  };\n  layers: ResolvedFarmLayer[];\n}\n\nconst FARM_CORE_PACKAGE = \"@farm.js/core\";\nconst FARM_CONFIG_ENTRY = \"@farm.js/core/config\";\nconst FARM_CORE_REFERENCE_RE = /([\"'])@farm.js\\/core\\1/g;\nconst FARM_CONFIG_HELPER_IMPORT_RE =\n  /(?:^|\\n)[\\t ]*import[\\t ]*\\{([^{}]*)\\}[\\t ]*from[\\t ]*([\"'])@farm.js\\/core\\2[\\t ]*;?[\\t ]*(?:\\n|$)/g;\nconst FARM_CONFIG_HELPER_SPECIFIER_RE =\n  /^(?:defineConfig|defineFarmConfig)(?:\\s+as\\s+[$A-Z_a-z][$\\w]*)?$/;\n\nconst CONFIG_FILENAMES = [\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n];\n\nconst LAYER_LOCAL_CONFIG_KEYS = new Set([\n  \"root\",\n  \"srcDir\",\n  \"outDir\",\n  \"distDir\",\n  \"deploy\",\n  \"output\",\n  \"preset\",\n  \"publicDir\",\n  \"generateBuildId\",\n]);\n\ntype LoadedLayer = ResolvedFarmLayer & {\n  config: Record<string, any>;\n};\n\nexport async function resolveFarmLayers<TConfig extends Record<string, any>>(\n  projectConfig: TConfig,\n  options: ResolveFarmLayersOptions,\n): Promise<FarmLayerResolution<TConfig>> {\n  const projectRoot = path.resolve(options.root);\n  const entries = normalizeLayerEntries(projectConfig.extends, \"project config\");\n\n  if (entries.length === 0) {\n    return {\n      config: {\n        ...projectConfig,\n        layers: [],\n      },\n      layers: [],\n    };\n  }\n\n  const loadedLayers: LoadedLayer[] = [];\n  const visited = new Set<string>();\n  const aliases = new Map<string, string>();\n\n  const visit = async (\n    source: string,\n    ownerRoot: string,\n    stack: Array<{ root: string; source: string }>,\n  ): Promise<void> => {\n    const resolvedSource = resolveLayerSource(source, ownerRoot);\n    const cycleIndex = stack.findIndex((entry) => entry.root === resolvedSource.root);\n    if (cycleIndex !== -1) {\n      const cycle = [...stack.slice(cycleIndex).map((entry) => entry.source), source];\n      throw new Error(`Farm layer cycle detected: ${cycle.join(\" -> \")}`);\n    }\n    if (visited.has(resolvedSource.root)) return;\n\n    const configFile = findFarmConfigFile(resolvedSource.root, resolvedSource.configFile);\n    const config = configFile\n      ? await loadFarmConfigFile(configFile, {\n          cacheRoot: projectRoot,\n          root: resolvedSource.root,\n        })\n      : {};\n    const nestedEntries = normalizeLayerEntries(config.extends, `layer ${JSON.stringify(source)}`);\n    const nextStack = [...stack, { root: resolvedSource.root, source }];\n\n    for (const nestedSource of nestedEntries) {\n      await visit(nestedSource, resolvedSource.root, nextStack);\n    }\n\n    if (visited.has(resolvedSource.root)) return;\n\n    const name = getLayerName(source, resolvedSource.root);\n    const conflictingRoot = aliases.get(name);\n    if (conflictingRoot && conflictingRoot !== resolvedSource.root) {\n      throw new Error(\n        `Farm layer alias \"#layers/${name}\" is ambiguous between ${conflictingRoot} and ${resolvedSource.root}`,\n      );\n    }\n    aliases.set(name, resolvedSource.root);\n\n    visited.add(resolvedSource.root);\n    loadedLayers.push({\n      source,\n      name,\n      root: resolvedSource.root,\n      srcDir: normalizeLayerSrcDir(config.srcDir),\n      configFile,\n      config,\n    });\n  };\n\n  for (const source of entries) {\n    await visit(source, projectRoot, []);\n  }\n\n  let mergedConfig: Record<string, any> = {};\n  for (const layer of loadedLayers) {\n    mergedConfig = mergeFarmLayerConfig(mergedConfig, getLayerDefaults(layer.config));\n  }\n  mergedConfig = mergeFarmLayerConfig(mergedConfig, projectConfig);\n\n  const layers = loadedLayers.map(({ config: _config, ...layer }) => layer);\n  return {\n    config: {\n      ...mergedConfig,\n      root: projectConfig.root,\n      srcDir: projectConfig.srcDir,\n      extends: projectConfig.extends,\n      layers,\n    } as unknown as FarmLayerResolution<TConfig>[\"config\"],\n    layers,\n  };\n}\n\nexport function getFarmSourceRoots(config: {\n  root?: string;\n  srcDir?: string;\n  layers?: readonly ResolvedFarmLayer[];\n}): FarmSourceRoot[] {\n  const roots: FarmSourceRoot[] = (config.layers ?? []).map((layer) => ({\n    name: layer.name,\n    root: layer.root,\n    srcDir: layer.srcDir,\n    layer: true,\n  }));\n\n  roots.push({\n    name: \"project\",\n    root: path.resolve(config.root || process.cwd()),\n    srcDir: config.srcDir || \"src\",\n    layer: false,\n  });\n\n  return roots;\n}\n\nexport function getFarmAppDirectories(config: {\n  root?: string;\n  srcDir?: string;\n  layers?: readonly ResolvedFarmLayer[];\n}): string[] {\n  return getFarmSourceRoots(config).map((source) => path.join(source.root, source.srcDir, \"app\"));\n}\n\nexport function getFarmLayerAliases(\n  layers: readonly ResolvedFarmLayer[] | undefined,\n): Record<string, string> {\n  return Object.fromEntries(\n    (layers ?? []).map((layer) => [`#layers/${layer.name}`, path.join(layer.root, layer.srcDir)]),\n  );\n}\n\n// Matches Windows drive-letter (`E:\\`, `E:/`) and UNC (`\\\\server\\share`) paths,\n// which would otherwise pass the \"bare specifier\" filter below. `path.isAbsolute`\n// only recognizes these on Windows, but esbuild can hand us such paths on any\n// platform (e.g. in cross-platform tests), and no valid package name contains\n// `:` or starts with `\\`.\nconst WINDOWS_ABSOLUTE_PATH_RE = /^(?:[A-Za-z]:[\\\\/]|\\\\\\\\)/;\n\n// External paths are written verbatim into the bundled config's import\n// statements. Node's ESM loader accepts `/abs/path` specifiers on POSIX, but a\n// raw Windows path like `E:\\...` is parsed as a URL with protocol `e:` and\n// rejected, so absolute paths must be emitted as file:// URLs.\nfunction toExternalSpecifier(resolvedPath: string): string {\n  return path.isAbsolute(resolvedPath) ? pathToFileURL(resolvedPath).href : resolvedPath;\n}\n\nexport function createFarmConfigResolutionPlugin(options: {\n  transform: EsbuildTransform;\n}): import(\"esbuild\").Plugin {\n  const configEntryChecks = new Map<string, Promise<boolean>>();\n\n  return {\n    name: \"farm-config-package-resolution\",\n    setup(pluginBuild) {\n      pluginBuild.onResolve({ filter: /^@farm\\.js\\/core$/ }, async (args) => {\n        if (\n          args.pluginData?.farmConfigExternal ||\n          args.kind !== \"import-statement\" ||\n          !args.importer\n        ) {\n          return;\n        }\n\n        let configEntryCheck = configEntryChecks.get(args.importer);\n        if (!configEntryCheck) {\n          configEntryCheck = onlyImportsFarmConfigHelpers(args.importer, options.transform);\n          configEntryChecks.set(args.importer, configEntryCheck);\n        }\n        if (!(await configEntryCheck)) return;\n\n        const resolved = await pluginBuild.resolve(FARM_CONFIG_ENTRY, {\n          importer: args.importer,\n          kind: args.kind,\n          namespace: args.namespace,\n          resolveDir: args.resolveDir,\n          pluginData: { farmConfigExternal: true },\n        });\n        if (resolved.errors.length > 0 || !resolved.path) return;\n\n        return {\n          path: toExternalSpecifier(resolved.path),\n          external: true,\n          warnings: resolved.warnings,\n        };\n      });\n\n      pluginBuild.onResolve({ filter: /^[^./]/ }, async (args) => {\n        // The filter is meant to catch bare package specifiers, but Windows\n        // absolute paths (`E:\\...`) match it too — including the entry point\n        // itself, which esbuild rejects when marked external.\n        if (\n          args.kind === \"entry-point\" ||\n          path.isAbsolute(args.path) ||\n          WINDOWS_ABSOLUTE_PATH_RE.test(args.path)\n        ) {\n          return;\n        }\n        if (args.pluginData?.farmConfigExternal) return;\n\n        const resolved = await pluginBuild.resolve(args.path, {\n          importer: args.importer,\n          kind: args.kind,\n          namespace: args.namespace,\n          resolveDir: args.resolveDir,\n          pluginData: { farmConfigExternal: true },\n        });\n\n        if (resolved.errors.length > 0 || !resolved.path) {\n          return { path: args.path, external: true };\n        }\n\n        return {\n          path: toExternalSpecifier(resolved.path),\n          external: true,\n          warnings: resolved.warnings,\n        };\n      });\n    },\n  };\n}\n\nexport async function loadFarmConfigFile<TConfig = Record<string, any>>(\n  configPath: string,\n  options: { root: string; cacheRoot?: string },\n): Promise<TConfig> {\n  const { build, transform } = await import(\"esbuild\");\n  const cacheRoot = path.resolve(options.cacheRoot || options.root);\n  const configCacheDir = path.join(cacheRoot, \".farm\", \".config-loader\");\n  await mkdir(configCacheDir, { recursive: true });\n\n  const modulePath = path.join(\n    configCacheDir,\n    `farm-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n  );\n\n  await build({\n    absWorkingDir: path.resolve(options.root),\n    entryPoints: [path.resolve(configPath)],\n    outfile: modulePath,\n    bundle: true,\n    format: \"esm\",\n    platform: \"node\",\n    target: `node${process.versions.node.split(\".\")[0]}`,\n    plugins: [createFarmConfigResolutionPlugin({ transform })],\n    jsx: \"automatic\",\n    logLevel: \"silent\",\n    sourcemap: \"inline\",\n  });\n\n  const moduleUrl = `${pathToFileURL(modulePath).href}?t=${Date.now()}`;\n  try {\n    const loaded = await import(/* @vite-ignore */ moduleUrl);\n    const config = loaded.default || loaded;\n    if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n      throw new TypeError(`Farm config ${configPath} must export an object`);\n    }\n    return config as TConfig;\n  } finally {\n    await unlink(modulePath).catch(() => undefined);\n  }\n}\n\nasync function onlyImportsFarmConfigHelpers(\n  importer: string,\n  transform: EsbuildTransform,\n): Promise<boolean> {\n  try {\n    const source = readFileSync(importer, \"utf8\");\n    if (!source.includes(FARM_CORE_PACKAGE)) return false;\n\n    const transformed = await transform(source, {\n      format: \"esm\",\n      jsx: \"automatic\",\n      loader: getEsbuildLoader(importer),\n      sourcefile: importer,\n    });\n    const references = [...transformed.code.matchAll(FARM_CORE_REFERENCE_RE)];\n    if (references.length === 0) return false;\n\n    const safeImportRanges: Array<{ start: number; end: number }> = [];\n    for (const match of transformed.code.matchAll(FARM_CONFIG_HELPER_IMPORT_RE)) {\n      const specifiers = match[1]\n        .split(\",\")\n        .map((specifier) => specifier.trim())\n        .filter(Boolean);\n      if (\n        specifiers.length === 0 ||\n        !specifiers.every((specifier) => FARM_CONFIG_HELPER_SPECIFIER_RE.test(specifier))\n      ) {\n        continue;\n      }\n\n      const start = match.index ?? 0;\n      safeImportRanges.push({ start, end: start + match[0].length });\n    }\n\n    return references.every((reference) => {\n      const index = reference.index ?? -1;\n      return safeImportRanges.some((range) => index >= range.start && index < range.end);\n    });\n  } catch {\n    // Unsupported syntax or non-file importers retain the existing package resolution path.\n    return false;\n  }\n}\n\nfunction getEsbuildLoader(file: string): \"js\" | \"jsx\" | \"ts\" | \"tsx\" {\n  switch (path.extname(file)) {\n    case \".ts\":\n    case \".mts\":\n    case \".cts\":\n      return \"ts\";\n    case \".tsx\":\n      return \"tsx\";\n    case \".jsx\":\n      return \"jsx\";\n    default:\n      return \"js\";\n  }\n}\n\nfunction normalizeLayerEntries(value: unknown, owner: string): string[] {\n  if (value === undefined) return [];\n  if (!Array.isArray(value)) {\n    throw new TypeError(`${owner} \"extends\" must be an array of layer paths or package names`);\n  }\n\n  return value.map((entry, index) => {\n    if (typeof entry !== \"string\" || entry.trim() === \"\") {\n      throw new TypeError(`${owner} \"extends\" entry ${index} must be a non-empty string`);\n    }\n    return entry.trim();\n  });\n}\n\nfunction resolveLayerSource(\n  source: string,\n  ownerRoot: string,\n): { root: string; configFile?: string } {\n  if (isPathLayerSource(source)) {\n    const target = source.startsWith(\"file:\")\n      ? path.resolve(ownerRoot, source.slice(\"file:\".length))\n      : path.resolve(ownerRoot, source);\n    if (!existsSync(target)) {\n      throw new Error(`Cannot resolve Farm layer ${JSON.stringify(source)} from ${ownerRoot}`);\n    }\n\n    const stats = statSync(target);\n    const root = stats.isDirectory() ? target : path.dirname(target);\n    return {\n      root: normalizeRealPath(root),\n      configFile: stats.isFile() ? normalizeRealPath(target) : undefined,\n    };\n  }\n\n  const requireFromOwner = createRequire(path.join(ownerRoot, \"package.json\"));\n  let packageJsonPath: string | undefined;\n  try {\n    packageJsonPath = requireFromOwner.resolve(`${source}/package.json`);\n  } catch {\n    // Packages with an exports map often hide package.json. Resolve their entry and walk upward.\n  }\n\n  if (packageJsonPath) {\n    return { root: normalizeRealPath(path.dirname(packageJsonPath)) };\n  }\n\n  try {\n    const entryPath = requireFromOwner.resolve(source);\n    const packageRoot = findNearestPackageRoot(entryPath);\n    if (packageRoot) return { root: normalizeRealPath(packageRoot) };\n  } catch {\n    // Use the common error below so local and package failures have the same shape.\n  }\n\n  throw new Error(`Cannot resolve Farm layer package ${JSON.stringify(source)} from ${ownerRoot}`);\n}\n\nfunction findNearestPackageRoot(entryPath: string): string | null {\n  let current = statSync(entryPath).isDirectory() ? entryPath : path.dirname(entryPath);\n  while (true) {\n    if (existsSync(path.join(current, \"package.json\"))) return current;\n    const parent = path.dirname(current);\n    if (parent === current) return null;\n    current = parent;\n  }\n}\n\nfunction findFarmConfigFile(root: string, explicitPath?: string): string | undefined {\n  if (explicitPath) return explicitPath;\n  for (const fileName of CONFIG_FILENAMES) {\n    const candidate = path.join(root, fileName);\n    if (existsSync(candidate)) return candidate;\n  }\n  return undefined;\n}\n\nfunction getLayerName(source: string, root: string): string {\n  if (!isPathLayerSource(source)) {\n    const packageName = source.split(\"/\").filter(Boolean).pop();\n    if (packageName) return sanitizeLayerName(packageName);\n  }\n\n  try {\n    const packageJson = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\"));\n    if (typeof packageJson.name === \"string\") {\n      return sanitizeLayerName(packageJson.name.split(\"/\").pop() || packageJson.name);\n    }\n  } catch {\n    // A local layer does not need package metadata.\n  }\n\n  return sanitizeLayerName(path.basename(root));\n}\n\nfunction sanitizeLayerName(value: string): string {\n  const name = value\n    .trim()\n    .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\");\n  if (!name) throw new Error(`Cannot derive a name for Farm layer ${JSON.stringify(value)}`);\n  return name;\n}\n\nfunction normalizeLayerSrcDir(value: unknown): string {\n  if (value === undefined) return \"src\";\n  if (typeof value !== \"string\" || value.trim() === \"\" || path.isAbsolute(value)) {\n    throw new TypeError(\"A Farm layer srcDir must be a non-empty relative path\");\n  }\n  const normalized = path.normalize(value.trim());\n  if (normalized === \"..\" || normalized.startsWith(`..${path.sep}`)) {\n    throw new TypeError(\"A Farm layer srcDir cannot leave the layer root\");\n  }\n  return normalized;\n}\n\nfunction getLayerDefaults(config: Record<string, any>): Record<string, any> {\n  return Object.fromEntries(\n    Object.entries(config).filter(\n      ([key, value]) =>\n        key !== \"extends\" && value !== undefined && !LAYER_LOCAL_CONFIG_KEYS.has(key),\n    ),\n  );\n}\n\nfunction mergeFarmLayerConfig(\n  base: Record<string, any>,\n  override: Record<string, any>,\n): Record<string, any> {\n  const output: Record<string, any> = { ...base };\n\n  for (const [key, value] of Object.entries(override)) {\n    if (value === undefined || key === \"layers\") continue;\n\n    if (key === \"plugins\") {\n      output[key] = [...toArray(output[key]), ...toArray(value)];\n      continue;\n    }\n\n    if (key === \"middleware\" && output[key] !== undefined) {\n      output[key] = [...toArray(output[key]), ...toArray(value)];\n      continue;\n    }\n\n    if ((key === \"redirects\" || key === \"rewrites\" || key === \"headers\") && output[key]) {\n      output[key] = mergeConfigListResolvers(output[key], value);\n      continue;\n    }\n\n    if (isPlainObject(output[key]) && isPlainObject(value)) {\n      output[key] = mergePlainObjects(output[key], value);\n      continue;\n    }\n\n    output[key] = value;\n  }\n\n  return output;\n}\n\nfunction mergePlainObjects(base: Record<string, any>, override: Record<string, any>) {\n  const output: Record<string, any> = { ...base };\n  for (const [key, value] of Object.entries(override)) {\n    if (value === undefined) continue;\n    output[key] =\n      isPlainObject(output[key]) && isPlainObject(value)\n        ? mergePlainObjects(output[key], value)\n        : value;\n  }\n  return output;\n}\n\nfunction mergeConfigListResolvers(base: unknown, override: unknown) {\n  return async () => [...(await resolveConfigList(base)), ...(await resolveConfigList(override))];\n}\n\nasync function resolveConfigList(value: unknown): Promise<any[]> {\n  const resolved = typeof value === \"function\" ? await value() : value;\n  return toArray(resolved);\n}\n\nfunction toArray(value: unknown): any[] {\n  if (value === undefined || value === null) return [];\n  return Array.isArray(value) ? value : [value];\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, any> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction isPathLayerSource(source: string): boolean {\n  return (\n    source.startsWith(\".\") ||\n    source.startsWith(\"/\") ||\n    source.startsWith(\"file:\") ||\n    /^[a-zA-Z]:[\\\\/]/.test(source)\n  );\n}\n\nfunction normalizeRealPath(value: string): string {\n  return path.resolve(realpathSync(value));\n}\n","import type {\n  FarmConfig as BaseFarmConfig,\n  FarmMigrationCommand,\n  FarmMigrationsConfig,\n  FarmMigrationsUserConfig,\n  ResolvedFarmMigrationsConfig,\n} from \"./types\";\nimport type { DocsConfig } from \"@farming-labs/docs\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./docs/types\";\nimport type { FarmIntegrationsUserConfig } from \"./integrations\";\nimport type { FarmMarkdownResolvedConfig, FarmMarkdownUserConfig } from \"./markdown\";\nimport type { FarmObservabilityUserConfig } from \"./observability\";\nimport type { FarmMiddlewareConfig } from \"./middleware/types\";\nimport type { FarmPlugin } from \"./plugin\";\nimport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nimport type { FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nimport type { FarmEnvConfig, ResolvedFarmEnv } from \"./env\";\nimport type { UserConfig as ViteUserConfig } from \"vite\";\nimport { resolveIntegrationPlugins } from \"./integrations\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig } from \"./workflows\";\nimport { resolveCronConfig } from \"./cron\";\nimport { resolveEnv, setEnv } from \"./env\";\nimport {\n  resolveMdxConfig,\n  type FarmMdxResolvedConfig,\n  type FarmMdxUserConfig,\n} from \"./app-markdown-config\";\nimport {\n  normalizeRouteRules,\n  routeRulesToHeaders,\n  routeRulesToRedirects,\n  type FarmRouteRules,\n} from \"./route-rules\";\nimport {\n  resolveServerActionsConfig,\n  type FarmServerActionsConfig,\n  type ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nimport {\n  resolveFarmServerConfig,\n  type FarmServerConfig,\n  type ResolvedFarmServerConfig,\n} from \"./server-http\";\nimport {\n  loadFarmConfigFile,\n  resolveFarmLayers,\n  type FarmLayerEntry,\n  type ResolvedFarmLayer,\n} from \"./layers\";\nimport path from \"path\";\nimport { logger } from \"./utils\";\nimport { normalizeFarmDeploymentId } from \"./deployment\";\nimport { normalizeFarmConfigBasePath } from \"./base-path\";\nimport { resolveFarmDevtoolsConfig, type ResolvedFarmDevtoolsConfig } from \"./devtools-config\";\nimport {\n  resolveFarmDevIndicatorsConfig,\n  type FarmDevIndicatorsConfig,\n  type ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nimport {\n  resolveFarmImageConfig,\n  type FarmImageConfig,\n  type ResolvedFarmImageConfig,\n} from \"./image-config\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport type { FarmI18nUserConfig, ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport type { FarmCacheUserConfig } from \"./cache\";\nimport {\n  resolveFarmAuthConfig,\n  resolveFarmAuthIntegration,\n  type FarmAuthUserConfig,\n  type ResolvedFarmAuthConfig,\n} from \"./auth-config\";\nimport { resolveFarmPerformanceConfig, type ResolvedFarmPerformanceConfig } from \"./preload\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport {\n  farmCspBlocksFrameworkInlineScripts,\n  getFarmSecurityHeader,\n  resolveFarmSecurityConfig,\n  type FarmCspConfig,\n  type FarmCspDirectives,\n  type FarmCspDirectiveValue,\n  type FarmCspOptions,\n  type FarmSecurityConfig,\n  type ResolvedFarmCspConfig,\n  type ResolvedFarmSecurityConfig,\n} from \"./security\";\nimport { isFarmRedirectStatus } from \"./navigation-errors\";\nimport { resolveFarmThemeConfig } from \"./theme/config\";\nimport { resolveFarmAgentConfig, type ResolvedFarmAgentConfig } from \"./agent-config\";\nimport type { ResolvedFarmThemeConfig } from \"./theme/types\";\nimport { isReactRenderer, resolveFarmRenderer } from \"./renderer\";\nimport type { FarmRenderer } from \"./renderer\";\nimport { applyFarmDocsFrameworkAutoDetection } from \"./docs/framework-detect\";\nimport { resolveFarmAPIConfig, type ResolvedFarmAPIConfig } from \"./api/config\";\n\nconst FARM_RESOLVED_CUSTOM_CONTEXT = Symbol.for(\"farm.resolvedCustomContext\");\n\nexport type {\n  FarmDocsConfigInput,\n  FarmDocsNavigationConfig,\n  FarmDocsResolvedConfig,\n  FarmDocsSidebarItem,\n  FarmDocsUserConfig,\n} from \"./docs/types\";\nexport type {\n  FarmMarkdownResolvedConfig,\n  FarmMarkdownRouteInput,\n  FarmMarkdownUserConfig,\n} from \"./markdown\";\nexport type {\n  FarmMdxComponents,\n  FarmMdxResolvedConfig,\n  FarmMdxUserConfig,\n} from \"./app-markdown-config\";\nexport type {\n  FarmMigrationCommand,\n  FarmMigrationsConfig,\n  FarmMigrationsUserConfig,\n  ResolvedFarmMigrationsConfig,\n} from \"./types\";\nexport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nexport type { FarmCronJobConfig, FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nexport type {\n  FarmRouteRule,\n  FarmRouteRuleCors,\n  FarmRouteRuleRedirect,\n  FarmRouteRuleRenderMode,\n  FarmRouteRules,\n} from \"./route-rules\";\nexport type {\n  FarmServerActionsConfig,\n  ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nexport type {\n  FarmServerConfig,\n  FarmServerDuration,\n  FarmServerHealthConfig,\n  ResolvedFarmServerConfig,\n  ResolvedFarmServerHealthConfig,\n} from \"./server-http\";\nexport type { FarmLayerEntry, ResolvedFarmLayer } from \"./layers\";\nexport type {\n  FarmDevtoolsConfig,\n  FarmDevtoolsUserConfig,\n  ResolvedFarmDevtoolsConfig,\n} from \"./devtools-config\";\nexport type {\n  FarmBuildActivityPosition,\n  FarmDevIndicatorsConfig,\n  ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nexport type {\n  FarmPerformanceConfig,\n  FarmPreloadMode,\n  FarmPreloadUserConfig,\n  ResolvedFarmPerformanceConfig,\n  ResolvedFarmPreloadConfig,\n} from \"./preload\";\nexport type {\n  FarmImageConfig,\n  FarmImageFormat,\n  FarmImageLocalPattern,\n  FarmImageProvider,\n  FarmImageRemotePattern,\n  ResolvedFarmImageConfig,\n} from \"./image-config\";\nexport type {\n  FarmI18nCookieConfig,\n  FarmI18nDetectionSignal,\n  FarmI18nDirection,\n  FarmI18nRouting,\n  FarmI18nUserConfig,\n  ResolvedFarmI18nConfig,\n} from \"./i18n/types\";\nexport type {\n  FarmAuthConfig,\n  FarmAuthDatabaseConfig,\n  FarmAuthEmailAndPasswordConfig,\n  FarmAuthSessionConfig,\n  FarmAuthUserConfig,\n  ResolvedFarmAuthConfig,\n} from \"./auth-config\";\nexport type {\n  FarmCspConfig,\n  FarmCspDirectives,\n  FarmCspDirectiveValue,\n  FarmCspOptions,\n  FarmSecurityConfig,\n  ResolvedFarmCspConfig,\n  ResolvedFarmSecurityConfig,\n} from \"./security\";\nexport type {\n  FarmRenderer,\n  FarmRendererCapabilities,\n  FarmRendererCapabilitiesInput,\n  FarmRendererStreamingCapabilities,\n} from \"./renderer\";\nexport { defineRenderer } from \"./renderer\";\nexport type {\n  FarmAPIConfig,\n  FarmAPIConfigResolverContext,\n  FarmAPIConfigValue,\n  ResolvedFarmAPIConfig,\n} from \"./api/config\";\n\nexport interface RedirectConfig {\n  source: string;\n  destination: string;\n  permanent?: boolean;\n  statusCode?: import(\"./navigation-errors\").FarmRedirectStatus;\n}\n\nexport interface HeaderConfig {\n  source: string;\n  headers: Array<{\n    key: string;\n    value: string;\n  }>;\n}\n\nexport interface RewriteConfig {\n  source: string;\n  destination: string;\n}\n\n/** @deprecated Use FarmImageConfig. */\nexport type ImageConfig = FarmImageConfig;\n\n/** @deprecated Use FarmI18nUserConfig. */\nexport type I18nConfig = FarmI18nUserConfig;\n\nexport interface OpenAPIConfig {\n  enabled?: boolean;\n  route?: string;\n  /**\n   * Path where the raw OpenAPI spec is served as JSON, so agents and API tools\n   * can fetch it at a predictable URL. Set to `false` to disable.\n   *\n   * @default \"/openapi.json\"\n   */\n  specRoute?: string | false;\n  title?: string;\n  description?: string;\n  version?: string;\n  servers?: Array<{\n    url: string;\n    description?: string;\n  }>;\n  contact?: {\n    name?: string;\n    email?: string;\n    url?: string;\n  };\n  license?: {\n    name: string;\n    url?: string;\n  };\n}\n\nexport type MiddlewareConfig = FarmMiddlewareConfig;\n\nexport interface NotFoundConfig {\n  /** Path to a custom 404 page component (e.g., \"./src/app/not-found.tsx\") */\n  component?: string;\n}\n\nexport type FarmDeployTarget = \"vercel\" | \"cloudflare\" | \"netlify\" | \"node\" | string;\n\nexport interface FarmDeployConfig {\n  /**\n   * Deployment platform. When present, Farm picks the matching Nitro preset and\n   * output directory unless explicitly overridden.\n   */\n  target?: FarmDeployTarget;\n  /** Nitro preset override. Usually inferred from target. */\n  preset?: BaseFarmConfig[\"preset\"];\n  /** Deployable output directory, relative to project root unless absolute. */\n  outputDir?: string;\n  /** Alias for outputDir for terser config. */\n  output?: string;\n  /** Cloudflare Pages project name used by `farm deploy --cloudflare`. */\n  projectName?: string;\n  vercel?: {\n    outputDirectory?: string;\n    buildCommand?: string;\n    installCommand?: string;\n    framework?: string | null;\n  };\n  cloudflare?: {\n    outputDir?: string;\n    projectName?: string;\n  };\n  netlify?: {\n    outputDir?: string;\n    site?: string;\n  };\n}\n\nexport interface ResolvedFarmDeployConfig extends Omit<FarmDeployConfig, \"output\"> {\n  target?: FarmDeployTarget;\n  preset: BaseFarmConfig[\"preset\"];\n  outputDir: string;\n}\n\nexport interface FarmUserConfig extends Omit<BaseFarmConfig, \"vite\" | \"docs\" | \"env\" | \"layers\"> {\n  /** Reusable Farm directories or installed packages, applied from left to right. */\n  extends?: readonly FarmLayerEntry[];\n  /** Global plugins. Integration-bound plugins must be contributed through an integration. */\n  plugins?: FarmPlugin<any, any, any, any, unknown, false>[];\n  integrations?: FarmIntegrationsUserConfig;\n  /**\n   * Farm-native authentication. `true` enables email/password auth with\n   * server helpers from `@farm.js/auth/server` and React APIs from\n   * `@farm.js/auth/client`.\n   */\n  auth?: FarmAuthUserConfig;\n  /** Shared application data, route, ISR, and PPR cache. */\n  cache?: FarmCacheUserConfig;\n  migrations?: FarmMigrationsUserConfig;\n  /** Map portable cron schedules to ordinary GET API routes. */\n  cron?: FarmCronUserConfig | FarmCronResolvedConfig | false;\n  workflows?: FarmWorkflowsUserConfig | boolean;\n  preset?: BaseFarmConfig[\"preset\"];\n  deploy?: FarmDeployConfig;\n  docs?: FarmDocsUserConfig;\n  md?: FarmMarkdownUserConfig | boolean;\n  mdx?: FarmMdxUserConfig;\n  observability?: FarmObservabilityUserConfig;\n  trailingSlash?: boolean;\n  redirects?: () => Promise<RedirectConfig[]> | RedirectConfig[];\n  rewrites?: () => Promise<RewriteConfig[]> | RewriteConfig[];\n  headers?: () => Promise<HeaderConfig[]> | HeaderConfig[];\n\n  images?: ImageConfig;\n  publicDir?: string;\n\n  i18n?: FarmI18nUserConfig | false;\n  openapi?: OpenAPIConfig;\n\n  middleware?: FarmMiddlewareConfig;\n  routeRules?: FarmRouteRules;\n  context?: BaseFarmConfig[\"context\"];\n  /** Server ingress and trusted-proxy policy. */\n  server?: FarmServerConfig;\n  serverActions?: FarmServerActionsConfig;\n  /** Build identifier used to detect and recover from deployment version skew. */\n  deploymentId?: string;\n\n  notFound?: NotFoundConfig;\n\n  distDir?: string;\n  generateBuildId?: () => string | Promise<string>;\n  compress?: boolean;\n\n  devIndicators?: FarmDevIndicatorsConfig;\n\n  serverRuntimeConfig?: Record<string, any>;\n  publicRuntimeConfig?: Record<string, any>;\n\n  env?: FarmEnvConfig<any, any>;\n\n  vite?: ViteUserConfig | ((config: ViteUserConfig) => ViteUserConfig);\n\n  [key: string]: any;\n}\n\nexport interface ResolvedFarmConfig extends Required<\n  Omit<\n    FarmUserConfig,\n    | \"extends\"\n    | \"plugins\"\n    | \"vite\"\n    | \"deploy\"\n    | \"docs\"\n    | \"md\"\n    | \"mdx\"\n    | \"migrations\"\n    | \"cron\"\n    | \"workflows\"\n    | \"api\"\n    | \"env\"\n    | \"server\"\n    | \"serverActions\"\n    | \"devtools\"\n    | \"devIndicators\"\n    | \"images\"\n    | \"i18n\"\n    | \"auth\"\n    | \"performance\"\n    | \"security\"\n    | \"theme\"\n    | \"renderer\"\n    | \"agent\"\n  >\n> {\n  agent: ResolvedFarmAgentConfig;\n  /** @internal Tracks whether `context` came from user/layer config instead of the default noop. */\n  [FARM_RESOLVED_CUSTOM_CONTEXT]?: boolean;\n  root: string;\n  extends: readonly FarmLayerEntry[];\n  layers: ResolvedFarmLayer[];\n  plugins: FarmPlugin[];\n  vite: ViteUserConfig;\n  deploy: ResolvedFarmDeployConfig;\n  docs: FarmDocsResolvedConfig;\n  md: FarmMarkdownResolvedConfig;\n  mdx: FarmMdxResolvedConfig;\n  migrations: ResolvedFarmMigrationsConfig;\n  cron: FarmCronResolvedConfig;\n  workflows: FarmWorkflowsResolvedConfig;\n  api: ResolvedFarmAPIConfig;\n  env: ResolvedFarmEnv;\n  server: ResolvedFarmServerConfig;\n  serverActions: ResolvedFarmServerActionsConfig;\n  devtools: ResolvedFarmDevtoolsConfig;\n  devIndicators: ResolvedFarmDevIndicatorsConfig;\n  images: ResolvedFarmImageConfig;\n  i18n: ResolvedFarmI18nConfig;\n  auth: ResolvedFarmAuthConfig;\n  performance: ResolvedFarmPerformanceConfig;\n  security: ResolvedFarmSecurityConfig;\n  theme: ResolvedFarmThemeConfig;\n  renderer: FarmRenderer;\n  routeRules: FarmRouteRules;\n  notFound: NotFoundConfig;\n}\n\nexport function hasCustomFarmRouteContext(config: ResolvedFarmConfig): boolean {\n  return config[FARM_RESOLVED_CUSTOM_CONTEXT] === true;\n}\n\nexport type FarmLayerConfig = Omit<\n  FarmUserConfig,\n  | \"root\"\n  | \"outDir\"\n  | \"distDir\"\n  | \"deploy\"\n  | \"preset\"\n  | \"publicDir\"\n  | \"generateBuildId\"\n  | \"deploymentId\"\n>;\n\nexport { defineConfig, defineFarmConfig } from \"./config-entry\";\n\nexport function normalizeDeployTarget(target?: FarmDeployTarget): FarmDeployTarget | undefined {\n  if (!target) return undefined;\n  if (target === \"cloudflare-pages\" || target === \"cloudflare_pages\") return \"cloudflare\";\n  if (target === \"node-server\" || target === \"nitro\") return \"node\";\n  return target;\n}\n\nexport function getPresetForDeployTarget(\n  target?: FarmDeployTarget,\n): BaseFarmConfig[\"preset\"] | undefined {\n  switch (normalizeDeployTarget(target)) {\n    case \"vercel\":\n      return \"vercel\";\n    case \"cloudflare\":\n      return \"cloudflare-pages\";\n    case \"netlify\":\n      return \"netlify\";\n    case \"node\":\n      return \"node-server\";\n    default:\n      return undefined;\n  }\n}\n\nexport function getDeployTargetForPreset(preset?: string): FarmDeployTarget | undefined {\n  if (!preset) return undefined;\n  if (preset === \"vercel\" || preset === \"vercel-edge\") return \"vercel\";\n  if (preset === \"cloudflare\" || preset === \"cloudflare-pages\" || preset === \"cloudflare-module\") {\n    return \"cloudflare\";\n  }\n  if (preset === \"netlify\" || preset === \"netlify-edge\") return \"netlify\";\n  if (preset === \"node-server\") return \"node\";\n  return undefined;\n}\n\nexport function getDefaultDeployOutputDir(\n  target: FarmDeployTarget | undefined,\n  preset: string | undefined,\n  distDir: string,\n): string {\n  const normalizedTarget = normalizeDeployTarget(target) || getDeployTargetForPreset(preset);\n  if (normalizedTarget === \"vercel\") return \".vercel/output\";\n  return `${distDir}/.output`;\n}\n\nexport function resolveDeployOutputPath(root: string, outputDir: string): string {\n  return path.isAbsolute(outputDir) ? outputDir : path.join(root, outputDir);\n}\n\nconst PLATFORM_BUILD_ENV_TARGETS: ReadonlyArray<[string, FarmDeployTarget]> = [\n  [\"VERCEL\", \"vercel\"],\n  [\"NETLIFY\", \"netlify\"],\n  [\"CF_PAGES\", \"cloudflare\"],\n];\n\n/**\n * Deploy target announced by the build environment (VERCEL=1, NETLIFY=true,\n * CF_PAGES=1), or undefined outside platform CI.\n */\nexport function detectPlatformDeployTarget(\n  env: NodeJS.ProcessEnv = process.env,\n): FarmDeployTarget | undefined {\n  for (const [key, target] of PLATFORM_BUILD_ENV_TARGETS) {\n    if (env[key]) return target;\n  }\n  return undefined;\n}\n\nconst warnedPlatformMismatches = new Set<string>();\n\nexport function resolveDeployConfig(\n  config: Pick<FarmUserConfig, \"deploy\" | \"preset\" | \"distDir\">,\n  overrides: {\n    target?: FarmDeployTarget;\n    preset?: BaseFarmConfig[\"preset\"];\n    outputDir?: string;\n    /** Build environment consulted for platform detection. Tests inject this. */\n    env?: NodeJS.ProcessEnv;\n  } = {},\n): ResolvedFarmDeployConfig {\n  const deploy = config.deploy || {};\n  const distDir = config.distDir || \".farm\";\n  // An explicit preset override replaces the deployment plan, so the\n  // configured platform target must not keep steering the output. Otherwise\n  // `farm build --preset node-server` on an app configured for Vercel writes\n  // a node server into .vercel/output — a directory Vercel will deploy as\n  // Build Output API content.\n  const overrideTarget = normalizeDeployTarget(overrides.target);\n  let target = overrideTarget\n    ? overrideTarget\n    : overrides.preset\n      ? getDeployTargetForPreset(overrides.preset)\n      : normalizeDeployTarget(deploy.target);\n\n  // A platform build environment (Vercel, Netlify, Cloudflare Pages) can only\n  // deploy its own output shape. When nothing selects a preset, the\n  // node-server fallback would build an artifact the platform cannot serve,\n  // so honor the detected platform instead. An explicit configuration always\n  // wins; it just gets a warning when it cannot run where it is being built.\n  const detectedTarget = detectPlatformDeployTarget(overrides.env);\n  if (detectedTarget) {\n    const hasExplicitSelection = Boolean(\n      target || overrides.preset || deploy.preset || config.preset,\n    );\n    if (!hasExplicitSelection) {\n      target = detectedTarget;\n      if (!warnedPlatformMismatches.has(`select:${detectedTarget}`)) {\n        warnedPlatformMismatches.add(`select:${detectedTarget}`);\n        logger.info(\n          `Detected ${detectedTarget} build environment; using the ${detectedTarget} preset. Set deploy.target in farm.config.ts to override.`,\n        );\n      }\n    }\n  }\n  // A CLI --target override governs the preset too: keep a configured preset\n  // only when it targets the same platform, otherwise derive the preset from\n  // the override target. Mirrors how a --preset override recomputes the target\n  // above, so `farm build --target netlify` never ships Vercel-shaped output.\n  const configuredPreset = deploy.preset || config.preset;\n  const overrideTargetPreset =\n    overrideTarget && getDeployTargetForPreset(configuredPreset) !== overrideTarget\n      ? getPresetForDeployTarget(overrideTarget)\n      : undefined;\n  const preset =\n    overrides.preset ||\n    overrideTargetPreset ||\n    configuredPreset ||\n    getPresetForDeployTarget(target) ||\n    \"node-server\";\n  const resolvedTarget = target || getDeployTargetForPreset(preset);\n  if (detectedTarget && resolvedTarget !== detectedTarget) {\n    const mismatchKey = `mismatch:${resolvedTarget}:${detectedTarget}`;\n    if (!warnedPlatformMismatches.has(mismatchKey)) {\n      warnedPlatformMismatches.add(mismatchKey);\n      logger.warn(\n        `The configured deploy target \"${resolvedTarget ?? preset}\" cannot be served by ${detectedTarget}, but this build is running in a ${detectedTarget} build environment. Set deploy.target: \"${detectedTarget}\" in farm.config.ts to deploy there.`,\n      );\n    }\n  }\n  const platformOutput =\n    resolvedTarget === \"vercel\"\n      ? deploy.vercel?.outputDirectory\n      : resolvedTarget === \"cloudflare\"\n        ? deploy.cloudflare?.outputDir\n        : resolvedTarget === \"netlify\"\n          ? deploy.netlify?.outputDir\n          : undefined;\n  const outputDir =\n    overrides.outputDir ||\n    deploy.outputDir ||\n    deploy.output ||\n    platformOutput ||\n    getDefaultDeployOutputDir(resolvedTarget, preset, distDir);\n\n  return {\n    ...deploy,\n    target: resolvedTarget,\n    preset,\n    outputDir,\n  };\n}\n\nexport function resolveMigrationsConfig(\n  migrations: FarmMigrationsUserConfig | undefined,\n): ResolvedFarmMigrationsConfig {\n  if (!migrations) return { commands: [] };\n  if (Array.isArray(migrations)) return { commands: migrations };\n  return { commands: migrations.commands || [] };\n}\n\nexport const DOCS_CONFIG_FILENAMES = [\n  \"docs.config.ts\",\n  \"docs.config.tsx\",\n  \"docs.config.mts\",\n  \"docs.config.cts\",\n  \"docs.config.js\",\n  \"docs.config.jsx\",\n  \"docs.config.mjs\",\n  \"docs.config.cjs\",\n  \"docs.json\",\n];\n\nfunction normalizeDocsRoute(value: string | undefined, fallback = \"/docs\"): string {\n  const raw = (value || fallback).trim();\n  if (!raw || raw === \"/\") return \"/\";\n  const normalized = raw\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\/+/g, \"/\")\n    .replace(/^\\/?/, \"/\")\n    .replace(/\\/+$/, \"\");\n  return normalized || \"/\";\n}\n\nfunction docsRouteToEntry(route: string): string {\n  const entry = route.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n  return entry || \"docs\";\n}\n\nfunction normalizeDocsContentDir(value: string | undefined): string | undefined {\n  if (!value) return undefined;\n  const normalized = value.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n  return normalized || undefined;\n}\n\nasync function inferDocsContentDir(\n  root: string,\n  srcDir: string,\n  entry: string,\n): Promise<string | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const contentDir = path.resolve(root, srcDir, \"app\", entry);\n  if (!existsSync(contentDir)) return undefined;\n\n  const relativeContentDir = path.relative(root, contentDir);\n  if (relativeContentDir.startsWith(\"..\") || path.isAbsolute(relativeContentDir)) return undefined;\n\n  return normalizeDocsContentDir(relativeContentDir);\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction cloneSerializable(value: unknown, seen = new WeakSet<object>()): any {\n  if (value === null) return null;\n\n  const valueType = typeof value;\n  if (valueType === \"string\" || valueType === \"number\" || valueType === \"boolean\") {\n    return value;\n  }\n  if (valueType === \"undefined\" || valueType === \"function\" || valueType === \"symbol\") {\n    return undefined;\n  }\n  if (Array.isArray(value)) {\n    return value.map((item) => cloneSerializable(item, seen)).filter((item) => item !== undefined);\n  }\n  if (value instanceof Date) {\n    return value.toISOString();\n  }\n  if (isRecord(value)) {\n    if (seen.has(value)) return undefined;\n    seen.add(value);\n\n    const output: Record<string, any> = {};\n    for (const [key, nestedValue] of Object.entries(value)) {\n      const clonedValue = cloneSerializable(nestedValue, seen);\n      if (clonedValue !== undefined) {\n        output[key] = clonedValue;\n      }\n    }\n    return output;\n  }\n\n  return undefined;\n}\n\nfunction sanitizeDocsConfig(config: Partial<DocsConfig>): Partial<DocsConfig> {\n  return cloneSerializable(config) || {};\n}\n\nexport async function findDocsConfigPath(\n  rootDir: string,\n  configPath?: string,\n): Promise<string | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const root = path.resolve(rootDir || process.cwd());\n\n  if (configPath) {\n    const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n    if (!existsSync(resolvedPath)) {\n      throw new Error(`Could not find docs config at ${configPath}.`);\n    }\n    return path.resolve(resolvedPath);\n  }\n\n  for (const filename of DOCS_CONFIG_FILENAMES) {\n    const resolvedPath = path.join(root, filename);\n    if (existsSync(resolvedPath)) {\n      return resolvedPath;\n    }\n  }\n\n  return undefined;\n}\n\nexport async function loadDocsConfig(\n  rootDir: string,\n  configPath?: string,\n): Promise<{ config: Partial<DocsConfig>; configPath: string } | undefined> {\n  const fs = await import(\"fs/promises\");\n  const { pathToFileURL } = await import(\"url\");\n  const root = path.resolve(rootDir || process.cwd());\n  const resolvedPath = await findDocsConfigPath(root, configPath);\n\n  if (!resolvedPath) return undefined;\n\n  try {\n    if (resolvedPath.endsWith(\".json\")) {\n      const content = await fs.readFile(resolvedPath, \"utf8\");\n      return { config: JSON.parse(content), configPath: resolvedPath };\n    }\n\n    const { build } = await import(\"esbuild\");\n    const configCacheDir = path.join(root, \".farm\", \".config-loader\");\n    await fs.mkdir(configCacheDir, { recursive: true });\n    const modulePath = path.join(\n      configCacheDir,\n      `docs-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n    );\n\n    await build({\n      absWorkingDir: root,\n      entryPoints: [resolvedPath],\n      outfile: modulePath,\n      bundle: true,\n      format: \"esm\",\n      platform: \"node\",\n      target: `node${process.versions.node.split(\".\")[0]}`,\n      packages: \"external\",\n      jsx: \"automatic\",\n      logLevel: \"silent\",\n      sourcemap: \"inline\",\n    });\n\n    const moduleUrl = pathToFileURL(modulePath).href + `?t=${Date.now()}`;\n    let importedConfig: any;\n\n    try {\n      importedConfig = await import(/* @vite-ignore */ moduleUrl);\n    } finally {\n      await fs.unlink(modulePath).catch(() => undefined);\n    }\n\n    return {\n      config: importedConfig.default || importedConfig,\n      configPath: resolvedPath,\n    };\n  } catch (error: any) {\n    const relativePath = path.relative(root, resolvedPath) || resolvedPath;\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Failed to load docs config from ${relativePath}: ${message}`);\n  }\n}\n\nexport async function resolveDocsConfig(\n  userDocs: FarmDocsUserConfig | undefined,\n  options: {\n    root?: string;\n    srcDir?: string;\n  } = {},\n): Promise<FarmDocsResolvedConfig> {\n  const root = options.root || process.cwd();\n\n  if (userDocs === false) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const docsOptions = isRecord(userDocs) ? userDocs : {};\n  if (docsOptions.enabled === false) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const loadedConfig = await loadDocsConfig(root, docsOptions.configPath);\n  const hasExplicitDocsConfig = userDocs === true || isRecord(userDocs);\n\n  if (!hasExplicitDocsConfig && !loadedConfig) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const inlineDocsConfig = sanitizeDocsConfig(docsOptions.config || {});\n  const directDocsConfig = sanitizeDocsConfig({\n    ...docsOptions,\n    adapter: undefined,\n    enabled: undefined,\n    config: undefined,\n    configPath: undefined,\n  } as Partial<DocsConfig>);\n  const loadedDocsConfig = sanitizeDocsConfig(loadedConfig?.config || {});\n  const mergedDocsConfig: Partial<DocsConfig> = {\n    ...loadedDocsConfig,\n    ...inlineDocsConfig,\n    ...directDocsConfig,\n  };\n\n  const explicitRoute = typeof docsOptions.entry === \"string\" ? docsOptions.entry : undefined;\n  const configuredDocsPath =\n    typeof mergedDocsConfig.docsPath === \"string\" ? mergedDocsConfig.docsPath : undefined;\n  const configuredEntry =\n    typeof mergedDocsConfig.entry === \"string\" ? mergedDocsConfig.entry : undefined;\n  const entryRoute = normalizeDocsRoute(\n    configuredDocsPath || explicitRoute || (configuredEntry ? `/${configuredEntry}` : undefined),\n  );\n  const docsEntry =\n    explicitRoute && explicitRoute.startsWith(\"/\")\n      ? docsRouteToEntry(explicitRoute)\n      : docsRouteToEntry(configuredEntry || entryRoute);\n  const configuredContentDir = normalizeDocsContentDir(\n    docsOptions.contentDir || mergedDocsConfig.contentDir,\n  );\n  const contentDir =\n    configuredContentDir || (await inferDocsContentDir(root, options.srcDir || \"src\", docsEntry));\n\n  return {\n    enabled: true,\n    entry: entryRoute,\n    ...(docsOptions.adapter ? { adapter: docsOptions.adapter } : {}),\n    contentDir,\n    configPath: loadedConfig?.configPath,\n    config: {\n      ...mergedDocsConfig,\n      entry: docsEntry,\n      docsPath: entryRoute,\n      ...(contentDir ? { contentDir } : {}),\n    },\n  };\n}\n\nfunction validateRedirectConfigs(redirects: RedirectConfig[], field: string): RedirectConfig[] {\n  for (const [index, redirect] of redirects.entries()) {\n    validateConfigRouteSource(redirect.source, `${field}[${index}].source`);\n    if (redirect.statusCode !== undefined && !isFarmRedirectStatus(redirect.statusCode)) {\n      throw new RangeError(\n        `${field}[${index}].statusCode must be one of 301, 302, 303, 307, or 308.`,\n      );\n    }\n  }\n  return redirects;\n}\n\nfunction validateConfigRouteSources<T extends { source: string }>(routes: T[], field: string): T[] {\n  for (const [index, route] of routes.entries()) {\n    validateConfigRouteSource(route.source, `${field}[${index}].source`);\n  }\n  return routes;\n}\n\nexport async function resolveConfig(\n  userConfig: FarmUserConfig,\n  mode: \"development\" | \"production\",\n): Promise<ResolvedFarmConfig> {\n  const projectRoot = userConfig.root || process.cwd();\n  const layerResolution = await resolveFarmLayers(userConfig, {\n    root: projectRoot,\n    mode,\n  });\n  userConfig = layerResolution.config;\n\n  if ((userConfig as Record<string, unknown>).typescript !== undefined) {\n    logger.warn(\n      'The top-level \"typescript\" option is not supported and has no effect. Configure TypeScript in `tsconfig.json` and run `tsc --noEmit` separately when builds must enforce project type errors.',\n    );\n  }\n\n  if ((userConfig as Record<string, unknown>).output !== undefined) {\n    logger.warn(\n      'The top-level \"output\" option is not supported and has no effect. Configure `deploy.target`, `deploy.preset`, or `deploy.outputDir` for deployment output, and use route rendering configuration for static pages.',\n    );\n  }\n\n  // The docs adapter runtime is React-only today; other renderers keep the\n  // embedded docs handler without any migration notice.\n  if (isReactRenderer(resolveFarmRenderer(userConfig.renderer))) {\n    userConfig = await applyFarmDocsFrameworkAutoDetection(userConfig, {\n      root: userConfig.root || projectRoot,\n    });\n  }\n\n  const redirects = validateRedirectConfigs(\n    typeof userConfig.redirects === \"function\"\n      ? await userConfig.redirects()\n      : userConfig.redirects || [],\n    \"redirects\",\n  );\n\n  const rewrites =\n    typeof userConfig.rewrites === \"function\"\n      ? await userConfig.rewrites()\n      : userConfig.rewrites || [];\n  validateConfigRouteSources(rewrites, \"rewrites\");\n\n  const headers =\n    typeof userConfig.headers === \"function\"\n      ? await userConfig.headers()\n      : userConfig.headers || [];\n  validateConfigRouteSources(headers, \"headers\");\n  const routeRules = normalizeRouteRules(userConfig.routeRules);\n  const routeRuleRedirects = routeRulesToRedirects(routeRules);\n  const routeRuleHeaders = routeRulesToHeaders(routeRules);\n  const security = resolveFarmSecurityConfig(userConfig.security);\n  const securityHeader = getFarmSecurityHeader(security);\n  if (farmCspBlocksFrameworkInlineScripts(security)) {\n    logger.warn(\n      \"security.csp restricts inline scripts (no 'unsafe-inline', nonce, or hash in \" +\n        \"script-src/default-src), which blocks the inline scripts Farm injects for theming \" +\n        \"and hydration. Add 'unsafe-inline' or the scripts' hashes until nonce support lands \" +\n        \"(https://github.com/farming-labs/farm.js/issues/1275).\",\n    );\n  }\n\n  const deploy = resolveDeployConfig(userConfig);\n  const root = userConfig.root || process.cwd();\n  const srcDir = userConfig.srcDir || \"src\";\n  const docs = await resolveDocsConfig(userConfig.docs, { root, srcDir });\n  const md = resolveMarkdownConfig(userConfig.md);\n  const mdx = resolveMdxConfig(userConfig.mdx);\n  const env = resolveEnv(userConfig.env, process.env);\n  setEnv(env);\n  const api = await resolveFarmAPIConfig(userConfig.api, { root, mode, env });\n  const auth = resolveFarmAuthConfig(userConfig.auth);\n  if (auth.enabled && userConfig.integrations?.auth) {\n    throw new Error(\n      \"Choose either the top-level `auth` config or `integrations.auth`; they cannot both own the auth route.\",\n    );\n  }\n  const nativeAuthIntegration = await resolveFarmAuthIntegration(auth, {\n    root,\n    mode,\n  });\n  const integrations = nativeAuthIntegration\n    ? { ...userConfig.integrations, auth: nativeAuthIntegration }\n    : userConfig.integrations || {};\n  const generateBuildId = userConfig.generateBuildId || (() => `build-${Date.now()}`);\n  const deploymentId = normalizeFarmDeploymentId(\n    userConfig.deploymentId ||\n      process.env.FARM_DEPLOYMENT_ID ||\n      process.env.VERCEL_GIT_COMMIT_SHA ||\n      process.env.CF_PAGES_COMMIT_SHA ||\n      (mode === \"production\" ? await generateBuildId() : \"development\"),\n  );\n  const basePath = normalizeFarmConfigBasePath(userConfig.basePath);\n  const openapi = {\n    enabled: false,\n    route: \"/docs/reference\",\n    specRoute: \"/openapi.json\" as string | false,\n    title: \"API Documentation\",\n    description: \"Auto-generated API documentation\",\n    version: \"1.0.0\",\n    servers: [{ url: \"http://localhost:3000\", description: \"Development server\" }],\n    ...userConfig.openapi,\n  };\n  if (openapi.route !== undefined) validateConfigRouteSource(openapi.route, \"openapi.route\");\n  if (openapi.specRoute) validateConfigRouteSource(openapi.specRoute, \"openapi.specRoute\");\n\n  const resolved: ResolvedFarmConfig = {\n    [FARM_RESOLVED_CUSTOM_CONTEXT]: typeof userConfig.context === \"function\",\n    root,\n    srcDir,\n    extends: userConfig.extends || [],\n    layers: layerResolution.layers,\n    outDir: userConfig.outDir || \"dist\",\n    basePath,\n    renderer: resolveFarmRenderer(userConfig.renderer),\n    preset: deploy.preset || \"node-server\",\n    deploy,\n    docs,\n    md,\n    mdx,\n    migrations: resolveMigrationsConfig(userConfig.migrations),\n    cron: resolveCronConfig(userConfig.cron),\n    workflows: resolveWorkflowsConfig(userConfig.workflows),\n    api,\n    observability: userConfig.observability ?? false,\n    telemetry: userConfig.telemetry !== false,\n    devtools: resolveFarmDevtoolsConfig(userConfig.devtools, mode),\n    storage: userConfig.storage || {},\n    cache: userConfig.cache || {},\n    auth,\n    suppressLintOnLink: userConfig.suppressLintOnLink ?? false,\n    experimental: {\n      serverComponents: false,\n      serverActions: false,\n      isolatedClientHydration: \"off\",\n      ppr: false,\n      ...userConfig.experimental,\n    },\n    agent: resolveFarmAgentConfig(userConfig.agent),\n    plugins: [...resolveIntegrationPlugins(integrations), ...(userConfig.plugins || [])],\n    integrations,\n    trailingSlash: userConfig.trailingSlash ?? false,\n    redirects: () => [...redirects, ...routeRuleRedirects],\n    rewrites: () => rewrites,\n    headers: () => [\n      ...headers,\n      ...routeRuleHeaders,\n      ...(securityHeader ? [{ source: \"/*\", headers: [securityHeader] }] : []),\n    ],\n    routeRules,\n    images: resolveFarmImageConfig(userConfig.images),\n    performance: resolveFarmPerformanceConfig(userConfig.performance),\n    theme: resolveFarmThemeConfig(userConfig.theme, basePath),\n    publicDir: userConfig.publicDir || \"public\",\n    i18n: resolveFarmI18nConfig(userConfig.i18n, { root, mode, basePath }),\n    openapi,\n    middleware: userConfig.middleware || {},\n    notFound: userConfig.notFound || {},\n    context: userConfig.context || (() => undefined),\n    server: resolveFarmServerConfig(userConfig.server),\n    serverActions: resolveServerActionsConfig(userConfig.serverActions),\n    security,\n    deploymentId,\n    distDir: userConfig.distDir || \".farm\",\n    generateBuildId,\n    compress: userConfig.compress ?? true,\n    devIndicators: resolveFarmDevIndicatorsConfig(userConfig.devIndicators, mode),\n    serverRuntimeConfig: userConfig.serverRuntimeConfig || {},\n    publicRuntimeConfig: userConfig.publicRuntimeConfig || {},\n    env,\n    vite: typeof userConfig.vite === \"function\" ? userConfig.vite({}) : userConfig.vite || {},\n  };\n\n  return resolved;\n}\n\nexport async function loadConfig(\n  rootDir?: string,\n  configPath?: string,\n  mode = process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n  loadEnvironment?: (typeof import(\"vite\"))[\"loadEnv\"],\n): Promise<FarmUserConfig | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const loadEnv = loadEnvironment || (await import(\"vite\")).loadEnv;\n\n  const root = rootDir || process.cwd();\n  const loadedEnv = loadEnv(mode, root, \"\");\n  for (const [key, value] of Object.entries(loadedEnv)) {\n    if (process.env[key] === undefined) {\n      process.env[key] = value;\n    }\n  }\n  // An explicitly supplied config path must resolve — silently falling back\n  // to the default config would run against the wrong configuration.\n  if (configPath) {\n    const explicitPath = path.resolve(\n      path.isAbsolute(configPath) ? configPath : path.join(root, configPath),\n    );\n    if (!existsSync(explicitPath)) {\n      throw new Error(`Config file not found at ${configPath} (resolved to ${explicitPath}).`);\n    }\n  }\n\n  const searchPaths = [\n    configPath,\n    \"farm.config.ts\",\n    \"farm.config.mts\",\n    \"farm.config.js\",\n    \"farm.config.mjs\",\n    \"config.ts\",\n    \"config.mts\",\n    \"config.js\",\n    \"config.mjs\",\n  ].filter(Boolean) as string[];\n\n  for (const relativePath of searchPaths) {\n    try {\n      // Use path.join for proper path construction\n      const absolutePath = path.isAbsolute(relativePath)\n        ? relativePath\n        : path.join(root, relativePath);\n\n      // Normalize the path to handle any issues\n      const normalizedPath = path.resolve(absolutePath);\n\n      // Check if file exists before trying to import\n      if (!existsSync(normalizedPath)) {\n        continue;\n      }\n\n      const loadedConfig = await loadFarmConfigFile<FarmUserConfig>(normalizedPath, { root });\n      return loadedConfig.root === undefined ? { ...loadedConfig, root } : loadedConfig;\n    } catch (error: any) {\n      const message = error instanceof Error ? error.message : String(error);\n      throw new Error(`Failed to load config from ${relativePath}: ${message}`);\n    }\n  }\n  return undefined;\n}\n","import path from \"node:path\";\nimport type {\n  FarmI18nDetectionSignal,\n  FarmI18nDirection,\n  FarmI18nUserConfig,\n  ResolvedFarmI18nConfig,\n} from \"./types\";\n\nexport const DEFAULT_FARM_I18N_COOKIE = \"farm_locale\";\nexport const DEFAULT_FARM_I18N_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\nconst DEFAULT_DETECTION: readonly FarmI18nDetectionSignal[] = [\"url\", \"cookie\", \"accept-language\"];\n\nexport function resolveFarmI18nConfig(\n  input: FarmI18nUserConfig | false | undefined,\n  options: { root?: string; mode?: \"development\" | \"production\"; basePath?: string } = {},\n): ResolvedFarmI18nConfig {\n  const root = options.root || process.cwd();\n  const basePath = options.basePath || \"/\";\n  const strictByDefault = options.mode === \"production\";\n\n  if (!input) {\n    return {\n      enabled: false,\n      basePath,\n      locales: [\"en\"],\n      defaultLocale: \"en\",\n      messages: path.join(root, \"src/messages\"),\n      routing: \"none\",\n      detection: [],\n      fallbackLocale: \"en\",\n      strict: strictByDefault,\n      cookie: {\n        name: DEFAULT_FARM_I18N_COOKIE,\n        maxAge: DEFAULT_FARM_I18N_COOKIE_MAX_AGE,\n        path: \"/\",\n        sameSite: \"lax\",\n        secure: options.mode === \"production\",\n      },\n      direction: {},\n    };\n  }\n\n  if (!Array.isArray(input.locales) || input.locales.length === 0) {\n    throw new Error(\"i18n.locales must contain at least one locale.\");\n  }\n\n  const locales = input.locales.map(canonicalizeLocale);\n  if (new Set(locales).size !== locales.length) {\n    throw new Error(\"i18n.locales must not contain duplicate locales.\");\n  }\n\n  const defaultLocale = canonicalizeLocale(input.defaultLocale);\n  if (!locales.includes(defaultLocale)) {\n    throw new Error(`i18n.defaultLocale \"${defaultLocale}\" must be included in i18n.locales.`);\n  }\n\n  const fallbackLocale = canonicalizeLocale(input.fallbackLocale || defaultLocale);\n  if (!locales.includes(fallbackLocale)) {\n    throw new Error(`i18n.fallbackLocale \"${fallbackLocale}\" must be included in i18n.locales.`);\n  }\n\n  const detection = resolveDetection(input);\n  const sameSite = input.cookie?.sameSite ?? \"lax\";\n  if (sameSite !== \"lax\" && sameSite !== \"strict\" && sameSite !== \"none\") {\n    throw new Error('i18n.cookie.sameSite must be \"lax\", \"strict\", or \"none\".');\n  }\n  const direction: Record<string, FarmI18nDirection> = {};\n  for (const [rawLocale, value] of Object.entries(input.direction || {})) {\n    const locale = canonicalizeLocale(rawLocale);\n    if (!locales.includes(locale)) {\n      throw new Error(`i18n.direction contains unknown locale \"${rawLocale}\".`);\n    }\n    if (value !== \"ltr\" && value !== \"rtl\") {\n      throw new Error(`i18n.direction.${rawLocale} must be \"ltr\" or \"rtl\".`);\n    }\n    direction[locale] = value;\n  }\n\n  return {\n    enabled: true,\n    basePath,\n    locales,\n    defaultLocale,\n    messages: path.resolve(root, input.messages || \"src/messages\"),\n    routing: input.routing || \"prefix-except-default\",\n    detection,\n    fallbackLocale,\n    strict: input.strict ?? strictByDefault,\n    cookie: {\n      name: input.cookie?.name?.trim() || DEFAULT_FARM_I18N_COOKIE,\n      maxAge: normalizePositiveInteger(\n        input.cookie?.maxAge,\n        DEFAULT_FARM_I18N_COOKIE_MAX_AGE,\n        \"i18n.cookie.maxAge\",\n      ),\n      path: normalizeCookiePath(input.cookie?.path),\n      sameSite,\n      secure: input.cookie?.secure ?? options.mode === \"production\",\n    },\n    direction,\n  };\n}\n\nexport function resolveFarmI18nMessagePath(\n  config: Pick<ResolvedFarmI18nConfig, \"messages\">,\n  locale: string,\n): string {\n  return config.messages.includes(\"{locale}\")\n    ? config.messages.split(\"{locale}\").join(locale)\n    : path.join(config.messages, `${locale}.json`);\n}\n\nexport function isFarmI18nCatalogFile(\n  config: Pick<ResolvedFarmI18nConfig, \"enabled\" | \"messages\" | \"locales\">,\n  file: string,\n): boolean {\n  if (!config.enabled) return false;\n  const normalizedFile = file.replace(/\\\\/g, \"/\");\n  return config.locales.some(\n    (locale) => resolveFarmI18nMessagePath(config, locale).replace(/\\\\/g, \"/\") === normalizedFile,\n  );\n}\n\nexport function canonicalizeLocale(locale: string): string {\n  if (!locale || typeof locale !== \"string\") {\n    throw new Error(\"Farm i18n locales must be non-empty strings.\");\n  }\n\n  try {\n    return Intl.getCanonicalLocales(locale)[0]!;\n  } catch {\n    throw new Error(`Invalid i18n locale \"${locale}\".`);\n  }\n}\n\nfunction resolveDetection(input: FarmI18nUserConfig): readonly FarmI18nDetectionSignal[] {\n  if (input.detection === false || input.localeDetection === false) {\n    return [\"url\"];\n  }\n\n  const detection = input.detection || DEFAULT_DETECTION;\n  const allowed = new Set<FarmI18nDetectionSignal>([\"url\", \"cookie\", \"accept-language\"]);\n  const unique: FarmI18nDetectionSignal[] = [];\n\n  for (const signal of detection) {\n    if (!allowed.has(signal)) {\n      throw new Error(`Unsupported i18n detection signal \"${signal}\".`);\n    }\n    if (!unique.includes(signal)) unique.push(signal);\n  }\n\n  return unique;\n}\n\nfunction normalizePositiveInteger(\n  value: number | undefined,\n  fallback: number,\n  name: string,\n): number {\n  if (value === undefined) return fallback;\n  if (!Number.isInteger(value) || value < 0) {\n    throw new Error(`${name} must be a positive integer.`);\n  }\n  return value;\n}\n\nfunction normalizeCookiePath(value: string | undefined): string {\n  if (value === undefined) return \"/\";\n  if (typeof value !== \"string\") {\n    throw new Error(\"i18n.cookie.path must be a root-relative pathname.\");\n  }\n\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(value)) {\n    throw new Error(\"i18n.cookie.path cannot contain backslashes or control characters.\");\n  }\n\n  const pathname = value.trim();\n  if (\n    !pathname ||\n    !pathname.startsWith(\"/\") ||\n    pathname.startsWith(\"//\") ||\n    pathname.includes(\";\") ||\n    pathname.includes(\"?\") ||\n    pathname.includes(\"#\")\n  ) {\n    throw new Error(\n      \"i18n.cookie.path must be a root-relative pathname without attributes, a query, or a hash.\",\n    );\n  }\n\n  for (const segment of pathname.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal and cannot conceal a separator or dot segment.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"i18n.cookie.path cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"i18n.cookie.path cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('i18n.cookie.path cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  return pathname;\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmIntegration } from \"./integrations\";\n\nexport interface FarmAuthEmailAndPasswordConfig {\n  /** Require a verified email before creating a session. @default false */\n  requireEmailVerification?: boolean;\n  /** Smallest accepted password length. @default 8 */\n  minPasswordLength?: number;\n  /** Largest accepted password length. @default 128 */\n  maxPasswordLength?: number;\n}\n\nexport interface FarmAuthSessionConfig {\n  /** Session lifetime in seconds. @default 604800 */\n  expiresIn?: number;\n  /** Session refresh interval in seconds. @default 86400 */\n  updateAge?: number;\n}\n\nexport interface FarmAuthDatabaseConfig {\n  /**\n   * Postgres connection string. Defaults to DATABASE_URL.\n   * Local development falls back to SQLite when no URL is present.\n   */\n  url?: string;\n  /** Local SQLite path. @default \".farm/auth.sqlite\" */\n  path?: string;\n  /** Automatically update the auth schema in development. @default true */\n  migrateInDevelopment?: boolean;\n}\n\nexport interface FarmAuthConfig {\n  /** Set false to disable auth without removing its configuration. @default true */\n  enabled?: boolean;\n  /** Display name used by authentication emails and metadata. */\n  appName?: string;\n  /** Route prefix for the auth endpoints. @default \"/api/auth\" */\n  basePath?: string;\n  /**\n   * Email/password authentication. It is enabled by default; set false to\n   * disable it when adding another sign-in method.\n   */\n  emailAndPassword?: boolean | FarmAuthEmailAndPasswordConfig;\n  session?: FarmAuthSessionConfig;\n  database?: FarmAuthDatabaseConfig;\n}\n\nexport type FarmAuthUserConfig = boolean | FarmAuthConfig;\n\nexport interface ResolvedFarmAuthConfig {\n  enabled: boolean;\n  appName?: string;\n  basePath: string;\n  emailAndPassword: {\n    enabled: boolean;\n    requireEmailVerification: boolean;\n    minPasswordLength: number;\n    maxPasswordLength: number;\n  };\n  session: {\n    expiresIn: number;\n    updateAge: number;\n  };\n  database: {\n    url?: string;\n    path: string;\n    migrateInDevelopment: boolean;\n  };\n}\n\ninterface FarmAuthRuntimeModule {\n  createFarmAuthIntegration(\n    config: ResolvedFarmAuthConfig,\n    options: {\n      root: string;\n      mode: \"development\" | \"production\";\n    },\n  ): FarmIntegration;\n}\n\nexport function resolveFarmAuthConfig(\n  input: FarmAuthUserConfig | undefined,\n): ResolvedFarmAuthConfig {\n  const config = input === true ? {} : input && typeof input === \"object\" ? input : {};\n  const passwordConfig = typeof config.emailAndPassword === \"object\" ? config.emailAndPassword : {};\n\n  const resolved: ResolvedFarmAuthConfig = {\n    enabled: input !== undefined && input !== false && config.enabled !== false,\n    appName: config.appName,\n    basePath: normalizeBasePath(config.basePath),\n    emailAndPassword: {\n      enabled: config.emailAndPassword !== false,\n      requireEmailVerification: passwordConfig.requireEmailVerification ?? false,\n      minPasswordLength: passwordConfig.minPasswordLength ?? 8,\n      maxPasswordLength: passwordConfig.maxPasswordLength ?? 128,\n    },\n    session: {\n      expiresIn: config.session?.expiresIn ?? 60 * 60 * 24 * 7,\n      updateAge: config.session?.updateAge ?? 60 * 60 * 24,\n    },\n    database: {\n      url: config.database?.url,\n      path: config.database?.path || \".farm/auth.sqlite\",\n      migrateInDevelopment: config.database?.migrateInDevelopment ?? true,\n    },\n  };\n\n  validateFarmAuthConfig(resolved);\n  return resolved;\n}\n\nexport async function resolveFarmAuthIntegration(\n  config: ResolvedFarmAuthConfig,\n  options: {\n    root: string;\n    mode: \"development\" | \"production\";\n  },\n): Promise<FarmIntegration | undefined> {\n  if (!config.enabled) return undefined;\n\n  const root = path.resolve(options.root);\n  let modulePath: string;\n  try {\n    const resolveFromApp = createRequire(path.join(root, \"package.json\"));\n    modulePath = resolveFromApp.resolve(\"@farm.js/auth/internal\");\n  } catch {\n    throw new Error(\n      \"The `auth` config requires @farm.js/auth. Install it with `pnpm add @farm.js/auth` and try again.\",\n    );\n  }\n\n  const runtime = (await import(\n    /* @vite-ignore */ pathToFileURL(modulePath).href\n  )) as FarmAuthRuntimeModule;\n  if (typeof runtime.createFarmAuthIntegration !== \"function\") {\n    throw new Error(\n      \"The installed @farm.js/auth package is incompatible with this version of @farm.js/core.\",\n    );\n  }\n\n  return runtime.createFarmAuthIntegration(config, {\n    ...options,\n    root,\n  });\n}\n\nfunction normalizeBasePath(value: string | undefined): string {\n  const route = (value || \"/api/auth\").trim();\n  if (!route) return \"/api/auth\";\n  assertStableBasePath(route);\n  const withLeadingSlash = route.startsWith(\"/\") ? route : `/${route}`;\n  const normalized = withLeadingSlash.replace(/\\/+/g, \"/\").replace(/\\/+$/, \"\");\n  return normalized || \"/api/auth\";\n}\n\nfunction assertStableBasePath(route: string): void {\n  if (route.includes(\"?\") || route.includes(\"#\")) {\n    throw new Error(\"auth.basePath cannot contain a query string or fragment.\");\n  }\n  if (route.startsWith(\"//\") || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(route)) {\n    throw new Error('auth.basePath must be an application pathname such as \"/api/auth\".');\n  }\n  if (hasUnstablePathCharacters(route)) {\n    throw new Error(\"auth.basePath cannot contain backslashes or control characters.\");\n  }\n  for (const segment of route.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal URL pathname segments.\n    }\n    if (hasUnstablePathCharacters(decoded) || decoded.includes(\"/\")) {\n      throw new Error(\"auth.basePath cannot contain encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('auth.basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n}\n\nfunction hasUnstablePathCharacters(value: string): boolean {\n  return (\n    value.includes(\"\\\\\") ||\n    Array.from(value).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  );\n}\n\nfunction validateFarmAuthConfig(config: ResolvedFarmAuthConfig): void {\n  const { minPasswordLength, maxPasswordLength } = config.emailAndPassword;\n  if (!Number.isInteger(minPasswordLength) || minPasswordLength < 1) {\n    throw new Error(\"auth.emailAndPassword.minPasswordLength must be a positive integer.\");\n  }\n  if (!Number.isInteger(maxPasswordLength) || maxPasswordLength < minPasswordLength) {\n    throw new Error(\n      \"auth.emailAndPassword.maxPasswordLength must be an integer greater than or equal to minPasswordLength.\",\n    );\n  }\n  if (!Number.isInteger(config.session.expiresIn) || config.session.expiresIn < 1) {\n    throw new Error(\"auth.session.expiresIn must be a positive integer.\");\n  }\n  if (!Number.isInteger(config.session.updateAge) || config.session.updateAge < 0) {\n    throw new Error(\"auth.session.updateAge must be a non-negative integer.\");\n  }\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * A rendering-library integration used by Farm's compiler, server renderer,\n * and browser hydration runtime.\n *\n * Renderer descriptors intentionally contain module identifiers instead of\n * implementation functions. This keeps farm.config.ts serializable and lets\n * every module resolve from the application that selected the renderer.\n */\nexport interface FarmRenderer {\n  /** Stable public identifier used in diagnostics and generated manifests. */\n  name: string;\n  /** Module exporting the renderer's Vite plugin factory. */\n  vite: string;\n  /** Module exporting Farm's server-renderer compatibility contract. */\n  server: string;\n  /** Module exporting Farm's browser-renderer compatibility contract. */\n  client: string;\n  /** JSX import source written to generated TypeScript configuration. */\n  jsxImportSource?: string;\n  /** Additional file extensions used for renderer-owned route components. */\n  componentExtensions?: readonly string[];\n  /** Packages that must share one module instance in a Farm application. */\n  dedupe?: readonly string[];\n  /** Renderer packages seeded into Vite's dependency optimizer. */\n  optimizeDeps?: readonly string[];\n  /**\n   * Scheduling policy for the production client and SSR graphs.\n   *\n   * Most renderer plugins are safe to run in parallel. Renderers whose\n   * compiler plugins keep process-global mutable state can opt into serial\n   * builds so one graph cannot invalidate the other's transforms.\n   */\n  buildConcurrency?: \"parallel\" | \"serial\";\n  /** Runtime features this renderer intentionally supports. */\n  capabilities?: FarmRendererCapabilitiesInput;\n  /**\n   * Serializable options consumed by the renderer's Vite integration.\n   *\n   * Keeping renderer-owned configuration on the descriptor lets one rendering\n   * library expose multiple compiler modes without teaching Farm's core about\n   * each option.\n   */\n  options?: Readonly<Record<string, unknown>>;\n}\n\nexport interface FarmRendererStreamingCapabilities {\n  /** Supports Node.js writable streams through renderToPipeableStream(). */\n  node: boolean;\n  /** Supports WHATWG ReadableStream output through renderToReadableStream(). */\n  web: boolean;\n}\n\nexport interface FarmRendererCapabilities {\n  streaming: FarmRendererStreamingCapabilities;\n  /**\n   * Whether re-rendering an existing root diffs the new tree against the live\n   * DOM instead of rebuilding it.\n   *\n   * Virtual-DOM renderers (React, Preact, Vue) compare the incoming tree with\n   * what is mounted, so a client navigation that re-renders a shared layout\n   * keeps the matching DOM nodes, their focus, and their component state.\n   *\n   * Compile-time fine-grained renderers (Solid, Svelte) have no virtual DOM to\n   * diff against. Their updates flow through bindings created when elements\n   * were constructed, so handing them a freshly materialized tree replaces the\n   * nodes. That is a property of those runtimes, not a gap in their adapters,\n   * and callers that need state to survive a re-render must keep it in a root\n   * they do not re-render rather than expect reconciliation here.\n   */\n  reconcilesRerenders: boolean;\n}\n\nexport interface FarmRendererCapabilitiesInput {\n  streaming?: Partial<FarmRendererStreamingCapabilities>;\n  reconcilesRerenders?: boolean;\n}\n\nconst DEFAULT_RENDERER_CAPABILITIES: Readonly<FarmRendererCapabilities> = Object.freeze({\n  streaming: Object.freeze({ node: false, web: false }),\n  // Conservative default: assume a re-render rebuilds until a renderer states\n  // otherwise, so callers do not silently rely on reconciliation.\n  reconcilesRerenders: false,\n});\n\nexport function getFarmRendererCapabilities(\n  renderer?: Pick<FarmRenderer, \"capabilities\">,\n): FarmRendererCapabilities {\n  return {\n    streaming: {\n      node: renderer?.capabilities?.streaming?.node ?? DEFAULT_RENDERER_CAPABILITIES.streaming.node,\n      web: renderer?.capabilities?.streaming?.web ?? DEFAULT_RENDERER_CAPABILITIES.streaming.web,\n    },\n    reconcilesRerenders:\n      renderer?.capabilities?.reconcilesRerenders ??\n      DEFAULT_RENDERER_CAPABILITIES.reconcilesRerenders,\n  };\n}\n\nexport const FARM_COMPONENT_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".jsx\"] as const;\n\nexport function resolveFarmComponentExtensions(extensions: readonly string[] = []): string[] {\n  return Array.from(\n    new Set(\n      [...FARM_COMPONENT_EXTENSIONS, ...extensions].map((extension) => {\n        const normalized = extension.trim().toLowerCase();\n        return normalized.startsWith(\".\") ? normalized : `.${normalized}`;\n      }),\n    ),\n  ).filter((extension) => extension.length > 1);\n}\n\nexport function getFarmRendererComponentExtensions(\n  renderer?: Pick<FarmRenderer, \"componentExtensions\">,\n): string[] {\n  return resolveFarmComponentExtensions(renderer?.componentExtensions);\n}\n\nexport interface FarmRendererViteModule {\n  createFarmRendererPlugin(options?: {\n    ssr?: boolean;\n    rendererOptions?: Readonly<Record<string, unknown>>;\n  }): unknown | readonly unknown[] | Promise<unknown | readonly unknown[]>;\n}\n\nexport interface FarmServerRendererRuntime {\n  readonly name: string;\n  readonly Fragment: unknown;\n  readonly Suspense: unknown;\n  createElement(type: unknown, props?: unknown, ...children: unknown[]): unknown;\n  isValidElement(value: unknown): boolean;\n  /** Wraps a route-owned client tree so compiled leaf boundaries stay inside that React root. */\n  wrapClientGraph?(element: unknown): unknown;\n  /**\n   * Optional: locate where a streamed chunk stops being the static shell.\n   *\n   * Partial prerendering caches everything before the first dynamic boundary\n   * and refreshes the rest on the client, so it has to know where that\n   * boundary is. The markers are renderer-specific (React streams Fizz\n   * boundary ids and `$RC`/`$RS` reveal calls, Solid streams `<template\n   * id=\"pl-N\">` with `$df(N)`), so the renderer that emits them owns finding\n   * them. Returns the index to cut at, or -1 when the chunk is entirely\n   * static.\n   *\n   * A renderer that does not implement this gets no static shell at all:\n   * guessing would mean caching a per-request response as if it were shared.\n   */\n  findStaticShellBoundary?(chunk: string): number;\n  renderToString(element: unknown): string | Promise<string>;\n  /**\n   * Optional variant for renderers whose components emit document-head markup\n   * during render (e.g. <svelte:head>). `html` is the body markup exactly as\n   * renderToString would produce it; `head` is injected into the assembled\n   * document's <head>.\n   */\n  renderToStringWithHead?(\n    element: unknown,\n  ): { html: string; head: string } | Promise<{ html: string; head: string }>;\n  /** Optional runtime copy of the descriptor capabilities for diagnostics. */\n  readonly capabilities?: FarmRendererCapabilities;\n  /** Optional bootstrap required before this renderer hydrates server markup. */\n  generateHydrationScript?: () => string;\n  /** Optional component used to render route-level failures. */\n  ErrorBoundary?: unknown;\n  /** Optional streaming primitive. Renderers without one use buffered SSR. */\n  renderToPipeableStream?: (\n    element: unknown,\n    callbacks: {\n      onShellReady(): void;\n      onShellError(error: unknown): void;\n      onError(error: unknown): void;\n    },\n  ) => { pipe(destination: NodeJS.WritableStream): void };\n  /** WHATWG streaming primitive used by Web-stream-capable renderers. */\n  renderToReadableStream?: (\n    element: unknown,\n  ) => ReadableStream<Uint8Array | string> | Promise<ReadableStream<Uint8Array | string>>;\n}\n\nexport const REACT_RENDERER: Readonly<FarmRenderer> = Object.freeze({\n  name: \"react\",\n  vite: \"@farm.js/core/renderer/react/vite\",\n  server: \"@farm.js/core/renderer/react/server\",\n  client: \"@farm.js/core/renderer/react/client\",\n  jsxImportSource: \"react\",\n  dedupe: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n  optimizeDeps: [\n    \"react\",\n    \"react-dom\",\n    \"react-dom/client\",\n    \"react/jsx-runtime\",\n    \"react/jsx-dev-runtime\",\n  ],\n  capabilities: {\n    streaming: { node: true, web: false },\n    reconcilesRerenders: true,\n  },\n});\n\nexport function defineRenderer<const TRenderer extends FarmRenderer>(\n  renderer: TRenderer,\n): TRenderer {\n  return renderer;\n}\n\nexport function resolveFarmRenderer(renderer?: FarmRenderer): FarmRenderer {\n  const resolved = renderer || REACT_RENDERER;\n  const fields = [\"name\", \"vite\", \"server\", \"client\"] as const;\n\n  for (const field of fields) {\n    if (typeof resolved[field] !== \"string\" || resolved[field].trim().length === 0) {\n      throw new TypeError(`Farm renderer \\`${field}\\` must be a non-empty string.`);\n    }\n  }\n\n  return {\n    ...resolved,\n    componentExtensions: [...(resolved.componentExtensions || [])],\n    dedupe: [...(resolved.dedupe || [])],\n    optimizeDeps: [...(resolved.optimizeDeps || [])],\n    buildConcurrency: resolved.buildConcurrency || \"parallel\",\n    capabilities: getFarmRendererCapabilities(resolved),\n    options: resolved.options ? { ...resolved.options } : undefined,\n  };\n}\n\nexport async function readFarmRendererWebStream(\n  stream: ReadableStream<Uint8Array | string>,\n): Promise<string> {\n  const reader = stream.getReader();\n  const decoder = new TextDecoder();\n  let html = \"\";\n\n  while (true) {\n    const { done, value } = await reader.read();\n    if (done) break;\n    html += typeof value === \"string\" ? value : decoder.decode(value, { stream: true });\n  }\n\n  return html + decoder.decode();\n}\n\nexport function isReactRenderer(renderer: Pick<FarmRenderer, \"name\"> | undefined): boolean {\n  return !renderer || renderer.name === \"react\";\n}\n\n/** Resolve an optional renderer module from the application's dependency graph. */\nexport function resolveFarmRendererModule(root: string, specifier: string): string {\n  const requireFromApp = createRequire(path.join(path.resolve(root), \"package.json\"));\n  return requireFromApp.resolve(specifier);\n}\n\nexport async function loadFarmRendererVitePlugins(\n  renderer: FarmRenderer,\n  root: string,\n  options: { ssr?: boolean } = {},\n): Promise<unknown[]> {\n  // React uses Vite's default automatic JSX transform today. Keep the legacy\n  // path dependency-free and avoid resolving Farm's own built package while\n  // running directly from source in the monorepo.\n  if (renderer.vite === REACT_RENDERER.vite) return [];\n\n  const modulePath = resolveFarmRendererModule(root, renderer.vite);\n  const rendererModule = (await import(pathToFileURL(modulePath).href)) as FarmRendererViteModule;\n\n  if (typeof rendererModule.createFarmRendererPlugin !== \"function\") {\n    throw new Error(\n      `Renderer \\`${renderer.name}\\` module ${renderer.vite} must export createFarmRendererPlugin().`,\n    );\n  }\n\n  const created = await rendererModule.createFarmRendererPlugin({\n    ...options,\n    rendererOptions: renderer.options,\n  });\n  if (!created) return [];\n  return Array.isArray(created) ? [...created] : [created];\n}\n","import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmDocsAdapterDescriptor, FarmDocsUserConfig } from \"./types\";\n\nconst FRAMEWORK_PACKAGE = \"@farming-labs/farmjs\";\nconst FRAMEWORK_CONFIG_ENTRY = \"@farming-labs/farmjs/config\";\n\n/**\n * The adapter descriptor protocol this core release knows how to drive.\n * Auto-detection must never wire up a descriptor from a future framework\n * release that this core cannot interpret; explicit withDocs() usage stays\n * the user's own call.\n */\nconst SUPPORTED_ADAPTER_PROTOCOL = 1;\n\nexport interface FarmDocsFrameworkDetectionOptions {\n  root: string;\n  log?: (message: string) => void;\n  warn?: (message: string) => void;\n}\n\n/**\n * Delegation triggers only for a dependency the app declared itself. A copy\n * that is merely resolvable through hoisting or a transitive dependency must\n * not silently change how the app's docs are served.\n */\nasync function frameworkDeclaredByApp(root: string): Promise<boolean> {\n  try {\n    const raw = await readFile(path.join(root, \"package.json\"), \"utf8\");\n    const manifest = JSON.parse(raw) as Record<string, unknown>;\n    for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n      const section = manifest[field];\n      if (section && typeof section === \"object\" && FRAMEWORK_PACKAGE in section) {\n        return true;\n      }\n    }\n  } catch {\n    // Unreadable manifest: treat as not declared and keep the embedded renderer.\n  }\n  return false;\n}\n\nconst emittedNotices = new Set<string>();\n\n/** Test hook: notices are once-per-process so dev-server restarts stay quiet. */\nexport function resetFarmDocsFrameworkDetectionNotices(): void {\n  emittedNotices.clear();\n}\n\nfunction noticeOnce(key: string, emit: (message: string) => void, message: string): void {\n  if (emittedNotices.has(key)) return;\n  emittedNotices.add(key);\n  emit(message);\n}\n\nfunction docsWantsFrameworkDetection(docs: FarmDocsUserConfig | undefined): boolean {\n  if (docs === true) return true;\n  if (!docs || typeof docs !== \"object\") return false;\n  if (docs.enabled === false) return false;\n  // An explicit descriptor means the app already wired an adapter; an\n  // explicit `false` is the opt-out that pins the embedded renderer.\n  if (docs.adapter !== undefined) return false;\n  return true;\n}\n\nfunction isSupportedAdapterDescriptor(value: unknown): value is FarmDocsAdapterDescriptor {\n  if (!value || typeof value !== \"object\") return false;\n  const descriptor = value as Partial<FarmDocsAdapterDescriptor>;\n  return (\n    descriptor.protocol === SUPPORTED_ADAPTER_PROTOCOL &&\n    typeof descriptor.server === \"string\" &&\n    descriptor.server.length > 0 &&\n    typeof descriptor.react === \"string\" &&\n    descriptor.react.length > 0\n  );\n}\n\n/**\n * Delegate `docs: {}` to the @farming-labs/farmjs docs framework when the app\n * has it installed (#483 phase 1).\n *\n * Detection applies the framework's own withDocs() to the user config, so the\n * result is byte-for-byte what a manual `withDocs(defineConfig(...))` produces:\n * the MDX Vite plugin plus the versioned adapter descriptor. When the package\n * is absent the embedded renderer keeps serving, with a one-time migration\n * notice. Any failure falls back to the embedded renderer instead of breaking\n * a working app.\n */\nexport async function applyFarmDocsFrameworkAutoDetection<\n  T extends { docs?: FarmDocsUserConfig; vite?: unknown },\n>(userConfig: T, options: FarmDocsFrameworkDetectionOptions): Promise<T> {\n  if (!docsWantsFrameworkDetection(userConfig.docs)) return userConfig;\n\n  const log = options.log ?? ((message: string) => console.log(message));\n  const warn = options.warn ?? ((message: string) => console.warn(message));\n  const root = path.resolve(options.root || process.cwd());\n\n  if (!(await frameworkDeclaredByApp(root))) {\n    noticeOnce(\n      \"embedded-fallback\",\n      warn,\n      `[farm] docs is served by the embedded renderer, which is being replaced by the ${FRAMEWORK_PACKAGE} docs framework. ` +\n        `Install ${FRAMEWORK_PACKAGE} (with @farming-labs/docs and @farming-labs/theme) to migrate now, ` +\n        \"or set docs.adapter = false to keep the embedded renderer and silence this notice.\",\n    );\n    return userConfig;\n  }\n\n  let configEntryPath: string;\n  try {\n    const requireFromApp = createRequire(path.join(root, \"package.json\"));\n    configEntryPath = requireFromApp.resolve(FRAMEWORK_CONFIG_ENTRY);\n  } catch {\n    noticeOnce(\n      \"declared-not-installed\",\n      warn,\n      `[farm] ${FRAMEWORK_PACKAGE} is declared in package.json but could not be resolved; ` +\n        \"keeping the embedded docs renderer. Run your package manager's install to enable docs delegation.\",\n    );\n    return userConfig;\n  }\n\n  try {\n    const frameworkConfig = await import(/* @vite-ignore */ pathToFileURL(configEntryPath).href);\n    const withDocs = frameworkConfig?.withDocs;\n    if (typeof withDocs !== \"function\") {\n      noticeOnce(\n        \"missing-withdocs\",\n        warn,\n        `[farm] ${FRAMEWORK_CONFIG_ENTRY} does not export withDocs(); keeping the embedded docs renderer.`,\n      );\n      return userConfig;\n    }\n\n    const applied = withDocs(userConfig);\n    const adapter = (applied as { docs?: { adapter?: unknown } } | undefined)?.docs?.adapter;\n    if (!isSupportedAdapterDescriptor(adapter)) {\n      noticeOnce(\n        \"unsupported-descriptor\",\n        warn,\n        `[farm] The installed ${FRAMEWORK_PACKAGE} release publishes a docs adapter this Farm version cannot drive ` +\n          `(need protocol ${SUPPORTED_ADAPTER_PROTOCOL}); keeping the embedded docs renderer. ` +\n          \"Upgrading @farm.js/core usually resolves this.\",\n      );\n      return userConfig;\n    }\n\n    noticeOnce(\n      \"delegated\",\n      log,\n      `[farm] docs: delegated to ${FRAMEWORK_PACKAGE} (detected in this app). ` +\n        \"Set docs.adapter = false to keep the embedded renderer.\",\n    );\n    return applied as T;\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    noticeOnce(\n      \"detect-failed\",\n      warn,\n      `[farm] Failed to load ${FRAMEWORK_CONFIG_ENTRY} (${message}); keeping the embedded docs renderer.`,\n    );\n    return userConfig;\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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wCAAmB,kBAAkB,OAAO;AAC5C,WAAO;AAAA,EACT,GAHmB;AAInB,QAAM,cAAc,4BAA4B,gBAAgB;AAEhE,SAAO;AAAA,IACL,MAAM,IAAI,SAAkB;AAC1B,UAAI,eAAe,sBAAsB,OAAO,GAAG;AACjD,eAAO,YAAY,UAAU,cAAc,SAAS,YAAY,YAAY;AAAA,MAC9E;AAEA,aAAO,iBAAiB,SAAS,MAAM,WAAW,CAAC;AAAA,IACrD;AAAA,IACA,MAAM,KAAK,SAAkB;AAC3B,UAAI,eAAgB,MAAM,uBAAuB,OAAO,GAAI;AAC1D,eAAO,YAAY,UAAU,cAAc,SAAS,YAAY,YAAY;AAAA,MAC9E;AAEA,aAAO;AAAA,QACL;AAAA,UACE,OAAO;AAAA,QACT;AAAA,QACA,EAAE,QAAQ,IAAI;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;AAhCgB;AAkCT,SAAS,yBACd,UAA8B,CAAC,GAC/B,kBACoB;AACpB,QAAM,WAAW,cAAc,SAAS,gBAAgB;AAExD,SAAO,sCAAe,yBAAyB,SAA4C;AACzF,QAAI,CAAC,qBAAqB,OAAO,EAAG,QAAO;AAE3C,UAAM,SAAS,QAAQ,OAAO,YAAY;AAC1C,QAAI,WAAW,SAAS,WAAW,QAAQ;AACzC,YAAM,WAAW,MAAM,SAAS,IAAI,OAAO;AAC3C,aAAO,WAAW,SAAS,aAAa,QAAQ,IAAI;AAAA,IACtD;AACA,QAAI,WAAW,QAAQ;AACrB,aAAO,SAAS,KAAK,OAAO;AAAA,IAC9B;AAEA,WAAO;AAAA,MACL;AAAA,QACE,OAAO;AAAA,MACT;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,OAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAAA,EACF,GAvBO;AAwBT;AA9BgB;","names":["memoryDriver","module","resolveDriver","base","import_node_fs","import_node_path","path","path","import_node_fs","import_node_path","path","import_node_fs","import_node_path","import_node_crypto","DOCS_FILE_EXTENSIONS","normalizeEntry","path","text","body","renderedSections","import_docs","globalState","path","path","text","resolveStorageRuntimeClient","createIntegrationOrm","response","import_node_path","env","globalState","import_node_fs","import_node_module","import_node_path","import_node_path","import_node_module","import_node_path","import_node_url","import_node_module","import_node_path","import_node_url","import_promises","import_node_module","import_node_path","import_node_url","existsSync","path","isRecord","pathToFileURL","isRecord","getDocsTitle","getDocsDescription","getLoadedDocsPages","toDocsSitemapPage","toDocsLlmsPage","getDocsLlmsOptions","getDocsDiscoveryOptions","buildFarmingDocsDiagnostics"]}