{"version":3,"sources":["../../src/storage/index.ts","../../src/integration-orm.ts","../../src/config-runtime.ts","../../src/base-path.ts","../../src/routing/specificity.ts","../../src/plugins/route-pattern.ts","../../src/request-origin.ts","../../src/integration-api.ts","../../src/plugin-integration-context.ts","../../src/utils/decode.ts","../../src/request-context.ts","../../src/server/response.ts","../../src/server-http.ts","../../src/integrations.ts","../../src/markdown.ts","../../src/utils.ts","../../src/workflows.ts","../../src/cron.ts","../../src/env.ts","../../src/app-markdown-config.ts","../../src/navigation-errors.ts","../../src/route-runtime.ts","../../src/route-rules.ts","../../src/server-action-security.ts","../../src/cache-invalidation.ts","../../src/layers.ts","../../src/config.ts","../../src/deployment.ts","../../src/devtools-config.ts","../../src/dev-indicators.ts","../../src/image-config.ts","../../src/i18n/config.ts","../../src/auth-config.ts","../../src/preload.ts","../../src/security.ts","../../src/theme/config.ts","../../src/agent-config.ts","../../src/renderer.ts","../../src/docs/framework-detect.ts","../../src/api/config.ts","../../src/build/production-vite.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 { loadConfig, resolveConfig, resolveDeployConfig } from \"./config\";\nexport { loadFarmProductionVite } from \"./build/production-vite\";\nexport type { FarmProductionViteRuntime } from \"./build/production-vite\";\nexport { logger } from \"./utils\";\n","const FARM_BASE_PATH = Symbol.for(\"farm.basePath\");\n\nfunction getFarmGlobalState(): Record<PropertyKey, unknown> {\n  return globalThis as unknown as Record<PropertyKey, unknown>;\n}\n\n/** @internal Configure the app-wide base path for framework link rendering. */\nexport function setFarmBasePath(basePath: string | undefined): void {\n  getFarmGlobalState()[FARM_BASE_PATH] = normalizeFarmBasePath(basePath);\n}\n\n/** @internal Read the app-wide base path used by framework links. */\nexport function getFarmBasePath(): string {\n  return (getFarmGlobalState()[FARM_BASE_PATH] as string | undefined) ?? \"\";\n}\n\nexport function applyFarmBasePath(href: string, basePath = getFarmBasePath()): string {\n  const normalizedBasePath = normalizeFarmBasePath(basePath);\n  if (!normalizedBasePath || !href.startsWith(\"/\") || href.startsWith(\"//\")) return href;\n  const canonicalHref = canonicalizeAppRelativeHref(href);\n  if (\n    canonicalHref === normalizedBasePath ||\n    canonicalHref.startsWith(`${normalizedBasePath}/`) ||\n    canonicalHref.startsWith(`${normalizedBasePath}?`) ||\n    canonicalHref.startsWith(`${normalizedBasePath}#`)\n  ) {\n    return canonicalHref;\n  }\n  return `${normalizedBasePath}${canonicalHref}`;\n}\n\nfunction canonicalizeAppRelativeHref(href: string): string {\n  const origin = \"http://farm.local\";\n  const resolved = new URL(href, origin);\n  if (resolved.origin !== origin) {\n    throw new Error(\"Farm app-relative href cannot change the URL origin.\");\n  }\n  return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\nexport function stripFarmBasePath(pathname: string, basePath = getFarmBasePath()): string {\n  const normalizedBasePath = normalizeFarmBasePath(basePath);\n  if (!normalizedBasePath) return pathname || \"/\";\n  if (pathname === normalizedBasePath) return \"/\";\n  if (!pathname.startsWith(`${normalizedBasePath}/`)) return pathname || \"/\";\n  return pathname.slice(normalizedBasePath.length) || \"/\";\n}\n\nexport function normalizeFarmBasePath(basePath: string | undefined): string {\n  if (!basePath || basePath === \"/\") return \"\";\n\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(basePath)) {\n    throw new Error(\"Farm basePath cannot contain backslashes or control characters.\");\n  }\n\n  const pathname = basePath.trim();\n  if (!pathname || pathname === \"/\") return \"\";\n  if (pathname.includes(\"?\") || pathname.includes(\"#\")) {\n    throw new Error(\"Farm basePath cannot contain a query string or hash.\");\n  }\n  if (pathname.startsWith(\"//\") || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(pathname)) {\n    throw new Error('Farm basePath must be a pathname such as \"/docs\", not a URL.');\n  }\n\n  for (const segment of pathname.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal in URL pathnames and cannot be dot segments.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"Farm basePath cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"Farm basePath cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('Farm basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  return `/${pathname}`.replace(/\\/{2,}/g, \"/\").replace(/\\/+$/, \"\");\n}\n\n/** Normalize a configured application base path while preserving `/` for root. */\nexport function normalizeFarmConfigBasePath(basePath: string | undefined): string {\n  return normalizeFarmBasePath(basePath) || \"/\";\n}\n","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 { localizeFarmHref, resolveFarmLocalePath } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { assertBrowserStableRoutePath } from \"../routing/specificity\";\n\ntype ConfigRoutePatternToken =\n  | { kind: \"param\"; name: string; captureIndex: number; catchAll: boolean }\n  | { kind: \"wildcard\"; captureIndex: number };\n\nexport interface CompiledConfigRoutePattern {\n  regex: RegExp;\n  tokens: ConfigRoutePatternToken[];\n}\n\nexport function validateConfigRouteSource(source: string, field = \"Config route source\"): string {\n  if (typeof source !== \"string\" || source.length === 0) {\n    throw new TypeError(`${field} must be a non-empty pathname pattern.`);\n  }\n  if (source.trim() !== source) {\n    throw new Error(`${field} cannot contain leading or trailing whitespace.`);\n  }\n  if (!source.startsWith(\"/\")) {\n    throw new Error(`${field} must start with \"/\".`);\n  }\n  if (source.includes(\"?\") || source.includes(\"#\")) {\n    throw new Error(`${field} must be a pathname without a query string or hash.`);\n  }\n  if (\n    source.includes(\"\\\\\") ||\n    Array.from(source).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  ) {\n    throw new Error(`${field} cannot contain backslashes or control characters.`);\n  }\n  assertBrowserStableRoutePath(source);\n  return source;\n}\n\nexport function resolveConfigRoutePathname(\n  pathname: string,\n  i18n?: ResolvedFarmI18nConfig,\n): { pathname: string; locale?: string } {\n  if (!i18n?.enabled) return { pathname: normalizeConfigRoutePathname(pathname) };\n  const match = resolveFarmLocalePath(pathname, i18n);\n  return { pathname: normalizeConfigRoutePathname(match.pathname), locale: match.locale };\n}\n\n/**\n * Drop a trailing slash before matching, mirroring `normalizeRuntimePath` in\n * the generated production matcher. Without this a request for `/old/` misses\n * a `/old` rule in dev while matching it in a built app.\n */\nfunction normalizeConfigRoutePathname(pathname: string): string {\n  if (!pathname || pathname === \"/\") return \"/\";\n  return pathname.endsWith(\"/\") ? pathname.replace(/\\/+$/, \"\") || \"/\" : pathname;\n}\n\nexport function localizeConfigRouteDestination(\n  destination: string,\n  locale: string | undefined,\n  i18n?: ResolvedFarmI18nConfig,\n): string {\n  return locale && i18n?.enabled ? localizeFarmHref(destination, locale, i18n) : destination;\n}\n\n/**\n * Append a catch-all capture, absorbing the separator that precedes it.\n *\n * The production matcher works on split segments and lets a non-terminal\n * catch-all consume zero of them (`minConsume = 0`), so `/x/*` + `/y` matches\n * `/x/y` and `/files/:path*` matches `/files`. Emitting a bare `(.*)` after a\n * literal `/` instead demands at least that separator, so the same rule was\n * inert in dev. Folding the slash into the optional group is how path-to-regexp\n * expresses the same thing, and it keeps one capture group so capture indexes\n * are unchanged (a non-participating group reads back as \"\").\n */\nfunction appendCatchAll(pattern: string): string {\n  return pattern.endsWith(\"/\") ? `${pattern.slice(0, -1)}(?:/(.*))?` : `${pattern}(.*)`;\n}\n\nfunction escapeRegexCharacter(character: string): string {\n  return /[\\\\^$.*+?()[\\]{}|]/.test(character) ? `\\\\${character}` : character;\n}\n\nexport function compileConfigRoutePattern(source: string): CompiledConfigRoutePattern {\n  validateConfigRouteSource(source);\n  const tokens: ConfigRoutePatternToken[] = [];\n  let pattern = \"\";\n  let captureIndex = 1;\n\n  for (let index = 0; index < source.length; ) {\n    const rest = source.slice(index);\n    const parameter = rest.match(/^:([A-Za-z0-9_]+)(\\*)?/);\n    if (parameter) {\n      tokens.push({\n        kind: \"param\",\n        name: parameter[1],\n        captureIndex,\n        catchAll: parameter[2] === \"*\",\n      });\n      pattern = parameter[2] ? appendCatchAll(pattern) : `${pattern}([^/]+)`;\n      captureIndex += 1;\n      index += parameter[0].length;\n      continue;\n    }\n\n    if (source[index] === \"*\") {\n      tokens.push({ kind: \"wildcard\", captureIndex });\n      pattern = appendCatchAll(pattern);\n      captureIndex += 1;\n      index += 1;\n      continue;\n    }\n\n    pattern += escapeRegexCharacter(source[index]);\n    index += 1;\n  }\n\n  return { regex: new RegExp(`^${pattern}$`), tokens };\n}\n\nexport function interpolateConfigRouteDestination(\n  destination: string,\n  match: RegExpMatchArray,\n  tokens: readonly ConfigRoutePatternToken[],\n): string {\n  const namedCaptures = new Map<string, string>();\n  const wildcardCaptures: string[] = [];\n  const captures = new Map<number, string>();\n\n  for (const token of tokens) {\n    const value = normalizeConfigRouteCapture(\n      match[token.captureIndex] || \"\",\n      token.kind === \"wildcard\" || token.catchAll,\n    );\n    captures.set(token.captureIndex, value);\n    if (token.kind === \"param\") {\n      namedCaptures.set(token.name, value);\n    } else {\n      wildcardCaptures.push(value);\n    }\n  }\n\n  let result = \"\";\n  let wildcardIndex = 0;\n  for (let index = 0; index < destination.length; ) {\n    const rest = destination.slice(index);\n    const parameter = rest.match(/^:([A-Za-z0-9_]+)(\\*)?/);\n    if (parameter) {\n      const value = namedCaptures.get(parameter[1]);\n      result += value === undefined ? parameter[0] : value;\n      index += parameter[0].length;\n      continue;\n    }\n\n    const capture = rest.match(/^\\$(\\d+)/);\n    if (capture) {\n      result += captures.get(Number(capture[1])) ?? \"\";\n      index += capture[0].length;\n      continue;\n    }\n\n    if (destination[index] === \"*\") {\n      result += wildcardCaptures[wildcardIndex] || \"\";\n      wildcardIndex += 1;\n      index += 1;\n      continue;\n    }\n\n    result += destination[index];\n    index += 1;\n  }\n\n  return result;\n}\n\nfunction normalizeConfigRouteCapture(value: string, catchAll: boolean): string {\n  const segments = catchAll ? value.split(\"/\").filter(Boolean) : [value];\n  return segments\n    .map((segment) => encodeConfigRouteSegment(decodeConfigRouteSegment(segment)))\n    .join(\"/\");\n}\n\nfunction decodeConfigRouteSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction encodeConfigRouteSegment(segment: string): string {\n  return encodeURIComponent(segment).replace(\n    /[!'()*]/g,\n    (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n}\n","/**\n * Shared request-origin primitives.\n *\n * Server actions and integration auth routes both need to decide whether a\n * state-changing request actually came from the app's own origin. The matching\n * rules (Origin/Referer resolution, Host fallback, wildcard subdomain patterns)\n * are security-sensitive and must not drift between the two, so they live here\n * and are consumed by both rather than reimplemented.\n *\n * These helpers never throw for untrusted input: callers map the failure\n * reasons onto their own error shapes.\n */\n\nexport type RequestOriginFailureReason = \"opaque-origin\" | \"invalid-origin\";\n\nexport type RequestSourceOriginResult =\n  /** `origin` is null when the request carried no Origin or Referer header. */\n  { ok: true; origin: string | null } | { ok: false; reason: RequestOriginFailureReason };\n\n/** Resolve the origin a request claims to come from, preferring Origin over Referer. */\nexport function getRequestSourceOrigin(request: Request): RequestSourceOriginResult {\n  const origin = request.headers.get(\"origin\")?.trim();\n  if (origin) {\n    return parseSourceOrigin(origin);\n  }\n\n  const referer = request.headers.get(\"referer\")?.trim();\n  if (referer) {\n    return parseSourceOrigin(referer);\n  }\n\n  return { ok: true, origin: null };\n}\n\nfunction parseSourceOrigin(value: string): RequestSourceOriginResult {\n  if (value === \"null\") {\n    return { ok: false, reason: \"opaque-origin\" };\n  }\n\n  try {\n    const parsed = new URL(value);\n    if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n      return { ok: false, reason: \"invalid-origin\" };\n    }\n    return { ok: true, origin: parsed.origin };\n  } catch {\n    return { ok: false, reason: \"invalid-origin\" };\n  }\n}\n\n/**\n * Accept a source origin whose host matches the `Host` header *and* whose\n * scheme matches the rebuilt `request.url` scheme. The scheme check blocks\n * browser-driven protocol-downgrade CSRF and also rejects proxy-rebuilt\n * `request.url` values whose scheme differs from the browser origin. For\n * TLS-terminating proxies that leave `request.url` as `http:`, enable\n * `trustProxy` with a proxy-emitted `X-Forwarded-Proto: https`, or add the\n * browser origin to `serverActions.allowedOrigins`.\n */\nexport function matchesHostHeader(sourceOrigin: string, request: Request): boolean {\n  const host = request.headers.get(\"host\")?.trim().toLowerCase();\n  if (!host) return false;\n\n  try {\n    const source = new URL(sourceOrigin);\n    const target = new URL(request.url);\n    return source.protocol === target.protocol && source.host.toLowerCase() === host;\n  } catch {\n    return false;\n  }\n}\n\nexport function matchesAllowedOrigin(sourceOrigin: string, pattern: string): boolean {\n  const source = new URL(sourceOrigin);\n  if (!pattern.includes(\"*\")) {\n    return pattern.includes(\"://\") ? source.origin === pattern : source.host === pattern;\n  }\n\n  const schemeEnd = pattern.indexOf(\"://\");\n  const scheme = schemeEnd === -1 ? null : pattern.slice(0, schemeEnd + 1);\n  const hostPattern = pattern.slice(schemeEnd === -1 ? 0 : schemeEnd + 3);\n  const [wildcardHost, port] = splitHostAndPort(hostPattern);\n  const baseHost = wildcardHost.slice(2);\n\n  if (scheme && source.protocol !== scheme) return false;\n  if (port && getEffectivePort(source) !== port) return false;\n  if (!port && source.port) return false;\n\n  return source.hostname.endsWith(`.${baseHost}`) && source.hostname !== baseHost;\n}\n\n/**\n * Validate and canonicalize a configured origin pattern. `label` names the\n * configuration field so the thrown message points at the user's own setting.\n */\nexport function normalizeAllowedOriginPattern(value: string, label: string): string {\n  const pattern = value.trim().toLowerCase();\n  if (!pattern) {\n    throw new TypeError(`${label} cannot contain empty values`);\n  }\n\n  if (pattern.includes(\"*\")) {\n    if (!/^(?:https?:\\/\\/)?\\*\\.[a-z0-9.-]+(?::\\d+)?$/.test(pattern)) {\n      throw new TypeError(`Invalid ${label} pattern: ${JSON.stringify(value)}`);\n    }\n    return pattern;\n  }\n\n  if (pattern.includes(\"://\")) {\n    let parsed: URL;\n    try {\n      parsed = new URL(pattern);\n    } catch {\n      throw new TypeError(`Invalid ${label} value: ${JSON.stringify(value)}`);\n    }\n\n    if (\n      (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n      parsed.username ||\n      parsed.password ||\n      parsed.pathname !== \"/\" ||\n      parsed.search ||\n      parsed.hash\n    ) {\n      throw new TypeError(`${label} must contain origins without paths: ${JSON.stringify(value)}`);\n    }\n    return parsed.origin;\n  }\n\n  if (/[/@?#]/.test(pattern)) {\n    throw new TypeError(`${label} must contain origins or hosts: ${JSON.stringify(value)}`);\n  }\n\n  try {\n    return new URL(`http://${pattern}`).host;\n  } catch {\n    throw new TypeError(`Invalid ${label} value: ${JSON.stringify(value)}`);\n  }\n}\n\nfunction splitHostAndPort(value: string): [string, string | null] {\n  const separator = value.lastIndexOf(\":\");\n  if (separator === -1) return [value, null];\n  return [value.slice(0, separator), value.slice(separator + 1)];\n}\n\nfunction getEffectivePort(url: URL): string {\n  if (url.port) return url.port;\n  if (url.protocol === \"https:\") return \"443\";\n  if (url.protocol === \"http:\") return \"80\";\n  return \"\";\n}\n","export type FarmIntegrationAPIMethod =\n  | \"GET\"\n  | \"QUERY\"\n  | \"POST\"\n  | \"PUT\"\n  | \"PATCH\"\n  | \"DELETE\"\n  | \"OPTIONS\"\n  | \"HEAD\";\n\nexport type FarmIntegrationAPIBodyFormat = \"json\" | \"form\" | \"none\";\nexport type FarmIntegrationAPIResponseFormat = \"json\" | \"text\" | \"response\";\n\nexport interface FarmIntegrationAPIOperation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n> {\n  readonly kind: \"farm-integration-api-operation\";\n  path: string;\n  method: TMethod;\n  bodyFormat?: FarmIntegrationAPIBodyFormat;\n  responseFormat?: FarmIntegrationAPIResponseFormat;\n  headers?: Record<string, string>;\n  credentials?: RequestCredentials;\n  isServer?: TServer;\n  __pathless?: boolean;\n  __types?: {\n    body: TBody;\n    query: TQuery;\n    response: TResponse;\n  };\n}\n\nexport type FarmIntegrationAPI = {\n  [key: string]: FarmIntegrationAPI | FarmIntegrationAPIOperation<any, any, any, any, any>;\n};\n\nexport type FarmIntegrationRouteOperationCarrier<\n  TPath extends string = string,\n  TOperation extends FarmIntegrationAPIOperation<any, any, any, any, any> =\n    FarmIntegrationAPIOperation<any, any, any, any, any>,\n> = {\n  path: TPath;\n  __operation: TOperation;\n};\n\ntype IntegrationAPIBuilderOptions<TServer extends boolean = false> = Omit<\n  FarmIntegrationAPIOperation<any, any, any, TServer>,\n  \"kind\" | \"method\" | \"path\" | \"__pathless\" | \"__types\"\n>;\n\nexport function defineIntegrationAPIOperation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n>(\n  operation: Omit<\n    FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>,\n    \"kind\" | \"__types\"\n  >,\n): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod> {\n  return {\n    kind: \"farm-integration-api-operation\",\n    ...operation,\n  };\n}\n\nexport function defineIntegrationAPI<TAPI extends FarmIntegrationAPI>(api: TAPI): TAPI {\n  return api;\n}\n\nfunction operation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n>(\n  method: TMethod,\n  pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n  maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod> {\n  const hasExplicitPath = typeof pathOrOptions === \"string\";\n  const path = hasExplicitPath ? pathOrOptions : \"\";\n  const options = (\n    hasExplicitPath\n      ? maybeOptions\n      : {\n          ...maybeOptions,\n          ...pathOrOptions,\n        }\n  ) as IntegrationAPIBuilderOptions<TServer>;\n\n  return defineIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>({\n    path,\n    method,\n    __pathless: !hasExplicitPath,\n    ...options,\n  });\n}\n\nfunction get<TResponse = unknown, TServer extends boolean = false>(\n  path: string,\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, never, TResponse, TServer, \"GET\">;\nfunction get<TQuery = never, TResponse = unknown, TServer extends boolean = false>(\n  path: string,\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"GET\">;\nfunction get<TResponse = unknown, TServer extends boolean = false>(\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, never, TResponse, TServer, \"GET\">;\nfunction get<TQuery = never, TResponse = unknown, TServer extends boolean = false>(\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"GET\">;\nfunction get(\n  pathOrOptions?: string | IntegrationAPIBuilderOptions<boolean>,\n  maybeOptions: IntegrationAPIBuilderOptions<boolean> = {} as IntegrationAPIBuilderOptions<boolean>,\n) {\n  return operation<never, any, any, boolean>(\"GET\", pathOrOptions, maybeOptions);\n}\n\nfunction isOperation(value: unknown): value is FarmIntegrationAPIOperation<any, any, any, any> {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (value as FarmIntegrationAPIOperation<any, any, any, any>).kind ===\n      \"farm-integration-api-operation\"\n  );\n}\n\nfunction bindRoutePath<TAPI extends FarmIntegrationAPI>(path: string, api: TAPI): TAPI {\n  const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n    if (isOperation(value)) {\n      return [\n        key,\n        {\n          ...value,\n          path,\n          __pathless: false,\n        },\n      ];\n    }\n\n    if (value && typeof value === \"object\") {\n      return [key, bindRoutePath(path, value as FarmIntegrationAPI)];\n    }\n\n    return [key, value];\n  });\n\n  return Object.fromEntries(entries) as TAPI;\n}\n\ntype RouteOperationsToAPI<\n  TOperations extends readonly FarmIntegrationAPIOperation<any, any, any, any, any>[],\n> = {\n  [TMethod in Lowercase<TOperations[number][\"method\"] & string>]: Extract<\n    TOperations[number],\n    { method: Uppercase<TMethod> }\n  >;\n};\n\ntype StripRouteClientPrefix<TPath extends string> = TPath extends `/api/${string}/${infer TRest}`\n  ? TRest\n  : TPath extends `/${string}/${infer TRest}`\n    ? TRest\n    : TPath extends `/${infer TRest}`\n      ? TRest\n      : TPath;\n\ntype NormalizeRouteSegment<TSegment extends string> = TSegment extends `[...${infer TName}]`\n  ? TName\n  : TSegment extends `[${infer TName}]`\n    ? TName\n    : TSegment extends `${infer TName}(${string}`\n      ? TName\n      : CamelCaseRouteSegment<TSegment>;\n\ntype CamelCaseRouteSegment<TSegment extends string> =\n  TSegment extends `${infer THead}-${infer TTail}`\n    ? `${THead}${Capitalize<CamelCaseRouteSegment<TTail>>}`\n    : TSegment;\n\ntype RouteNamespaceFromPath<\n  TPath extends string,\n  TOperation extends FarmIntegrationAPIOperation<any, any, any, any, any>,\n> = TPath extends `${infer THead}/${infer TTail}`\n  ? {\n      [TKey in NormalizeRouteSegment<THead>]: RouteNamespaceFromPath<TTail, TOperation>;\n    }\n  : {\n      [TKey in NormalizeRouteSegment<TPath>]: {\n        [TMethod in Lowercase<TOperation[\"method\"] & string>]: TOperation;\n      };\n    };\n\ntype UnionToIntersection<TUnion> = (\n  TUnion extends unknown ? (value: TUnion) => void : never\n) extends (value: infer TIntersection) => void\n  ? TIntersection\n  : never;\n\ntype ExpandRecursively<TValue> = TValue extends (...args: any[]) => any\n  ? TValue\n  : TValue extends object\n    ? { [TKey in keyof TValue]: ExpandRecursively<TValue[TKey]> }\n    : TValue;\n\ntype RoutesToAPI<TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[]> =\n  ExpandRecursively<\n    UnionToIntersection<\n      TRoutes[number] extends FarmIntegrationRouteOperationCarrier<infer TPath, infer TOperation>\n        ? RouteNamespaceFromPath<StripRouteClientPrefix<TPath>, TOperation>\n        : never\n    >\n  >;\n\nexport type InferIntegrationAPIFromRoutes<\n  TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[],\n> = RoutesToAPI<TRoutes>;\n\nfunction route<TAPI extends FarmIntegrationAPI>(path: string, definition: TAPI): TAPI;\nfunction route<TOperations extends readonly FarmIntegrationAPIOperation<any, any, any, any, any>[]>(\n  path: string,\n  ...operations: TOperations\n): RouteOperationsToAPI<TOperations>;\nfunction route(\n  path: string,\n  definitionOrOperation: FarmIntegrationAPI | FarmIntegrationAPIOperation<any, any, any, any, any>,\n  ...operations: readonly FarmIntegrationAPIOperation<any, any, any, any, any>[]\n) {\n  if (isOperation(definitionOrOperation)) {\n    const allOperations = [definitionOrOperation, ...operations];\n    return Object.fromEntries(\n      allOperations.map((operation) => [\n        operation.method.toLowerCase(),\n        {\n          ...operation,\n          path,\n          __pathless: false,\n        },\n      ]),\n    );\n  }\n\n  return bindRoutePath(path, definitionOrOperation as FarmIntegrationAPI);\n}\n\nfunction normalizeRouteSegment(segment: string): string {\n  if (!segment) {\n    return \"index\";\n  }\n\n  if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n    return segment.slice(4, -1) || \"index\";\n  }\n\n  if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n    return segment.slice(1, -1) || \"index\";\n  }\n\n  const matcherIndex = segment.indexOf(\"(\");\n  if (matcherIndex > 0) {\n    return segment.slice(0, matcherIndex);\n  }\n\n  return camelCaseRouteSegment(segment);\n}\n\nfunction camelCaseRouteSegment(segment: string): string {\n  return segment.replace(/-([a-zA-Z0-9])/g, (_match, value: string) => value.toUpperCase());\n}\n\nfunction getRouteClientSegments(path: string): string[] {\n  const segments = path.split(\"/\").filter(Boolean);\n  if (segments.length === 0) {\n    return [\"index\"];\n  }\n\n  const stripped =\n    segments[0] === \"api\" && segments.length > 2\n      ? segments.slice(2)\n      : segments.length > 1\n        ? segments.slice(1)\n        : [segments[segments.length - 1]];\n\n  return stripped.map(normalizeRouteSegment).filter(Boolean);\n}\n\nfunction setRouteOperation(\n  target: Record<string, unknown>,\n  pathSegments: string[],\n  operation: FarmIntegrationAPIOperation<any, any, any, any, any>,\n) {\n  const [head, ...tail] = pathSegments;\n  if (!head) {\n    return;\n  }\n\n  if (tail.length === 0) {\n    const leaf = ((target[head] as Record<string, unknown> | undefined) || {}) as Record<\n      string,\n      unknown\n    >;\n    leaf[operation.method.toLowerCase()] = {\n      ...operation,\n      path: operation.path,\n      __pathless: false,\n    };\n    target[head] = leaf;\n    return;\n  }\n\n  const branch = ((target[head] as Record<string, unknown> | undefined) || {}) as Record<\n    string,\n    unknown\n  >;\n  target[head] = branch;\n  setRouteOperation(branch, tail, operation);\n}\n\nfunction fromRoutes<TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[]>(\n  routes: TRoutes,\n): RoutesToAPI<TRoutes> {\n  const definition: Record<string, unknown> = {};\n\n  for (const route of routes) {\n    if (!isOperation(route.__operation)) {\n      continue;\n    }\n\n    setRouteOperation(definition, getRouteClientSegments(route.path), {\n      ...route.__operation,\n      path: route.path,\n      __pathless: false,\n    });\n  }\n\n  return definition as RoutesToAPI<TRoutes>;\n}\n\nexport const api = {\n  get,\n  route,\n  fromRoutes,\n  query<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"QUERY\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"QUERY\">(\"QUERY\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  post<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"POST\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"POST\">(\"POST\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  put<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PUT\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"PUT\">(\"PUT\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  patch<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PATCH\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"PATCH\">(\"PATCH\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  delete<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"DELETE\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"DELETE\">(\"DELETE\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  options<TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"OPTIONS\"> {\n    return operation<never, TQuery, TResponse, TServer, \"OPTIONS\">(\n      \"OPTIONS\",\n      pathOrOptions,\n      maybeOptions,\n    );\n  },\n  head<TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"HEAD\"> {\n    return operation<never, TQuery, TResponse, TServer, \"HEAD\">(\n      \"HEAD\",\n      pathOrOptions,\n      maybeOptions,\n    );\n  },\n  form: {\n    query<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"QUERY\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"QUERY\">(\"QUERY\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    post<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"POST\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"POST\">(\"POST\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    put<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PUT\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"PUT\">(\"PUT\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    patch<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PATCH\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"PATCH\">(\"PATCH\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    delete<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"DELETE\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"DELETE\">(\"DELETE\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n  },\n};\n\nexport const endpoint = api;\n","import type { FarmPlugin, FarmPluginIntegrationContext } from \"./plugin\";\n\nconst FARM_PLUGIN_INTEGRATION_CONTEXT = Symbol.for(\"@farm.js/core/plugin-integration-context\");\n\nexport function setFarmPluginIntegrationContext(\n  plugin: FarmPlugin,\n  integration: Readonly<FarmPluginIntegrationContext>,\n): void {\n  Object.defineProperty(plugin, FARM_PLUGIN_INTEGRATION_CONTEXT, {\n    value: integration,\n  });\n}\n\nexport function getFarmPluginIntegrationContext(\n  plugin: FarmPlugin,\n): Readonly<FarmPluginIntegrationContext> | undefined {\n  const value = (plugin as FarmPlugin & Record<symbol, unknown>)[FARM_PLUGIN_INTEGRATION_CONTEXT];\n  return value && typeof value === \"object\"\n    ? (value as Readonly<FarmPluginIntegrationContext>)\n    : undefined;\n}\n","/**\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 type { ServerResponse } from \"node:http\";\n\ninterface ResponseEventWatcher<T> {\n  promise: Promise<T>;\n  dispose(): void;\n}\n\n/**\n * Watch a real Node response without requiring every Node-compatible response\n * adapter or test double to extend EventEmitter. The framework only needs\n * disconnect handling when the response exposes both halves of the listener\n * lifecycle; otherwise callers can still send ordinary non-blocked bodies.\n */\nfunction watchResponseEvent<T>(\n  res: ServerResponse,\n  events: ReadonlyArray<readonly [event: string, value: T]>,\n): ResponseEventWatcher<T> | null {\n  if (typeof res.once !== \"function\" || typeof res.removeListener !== \"function\") {\n    return null;\n  }\n\n  let settled = false;\n  const listeners = events.map(([event, value]) => {\n    const listener = () => {\n      if (settled) return;\n      settled = true;\n      dispose();\n      resolvePromise(value);\n    };\n    return { event, listener };\n  });\n  let resolvePromise!: (value: T) => void;\n  const promise = new Promise<T>((resolve) => {\n    resolvePromise = resolve;\n    for (const { event, listener } of listeners) {\n      res.once(event, listener);\n    }\n  });\n  const dispose = () => {\n    for (const { event, listener } of listeners) {\n      res.removeListener(event, listener);\n    }\n  };\n\n  return { promise, dispose };\n}\n\n/**\n * Waits until the response can accept more writes. Resolves false when the\n * client is gone (close or error): a disconnected socket never emits drain,\n * so waiting on drain alone leaks the pending handler, its reader lock, and\n * the response body for the life of the process.\n */\nasync function waitForWritable(res: ServerResponse): Promise<boolean> {\n  if (res.writableEnded || res.destroyed) {\n    return false;\n  }\n\n  const watcher = watchResponseEvent(res, [\n    [\"drain\", true],\n    [\"close\", false],\n    [\"error\", false],\n  ]);\n  if (!watcher) {\n    return false;\n  }\n\n  try {\n    return await watcher.promise;\n  } finally {\n    watcher.dispose();\n  }\n}\n\n/**\n * Older Fetch implementations expose repeated Set-Cookie fields as one\n * comma-joined value. Split only at a comma followed by another cookie-pair;\n * commas inside Expires dates remain part of the current cookie. RFC cookie\n * values exclude commas, so a comma followed by a cookie-pair is unambiguous\n * for valid Set-Cookie syntax once the original field boundaries are lost.\n */\nfunction splitSetCookieHeader(value: string): string[] {\n  const cookies: string[] = [];\n  let start = 0;\n\n  for (let index = 0; index < value.length; index += 1) {\n    if (value[index] !== \",\") continue;\n\n    let next = index + 1;\n    while (value[next] === \" \" || value[next] === \"\\t\") next += 1;\n\n    const equals = value.indexOf(\"=\", next);\n    if (equals === -1) continue;\n\n    const separator = value.slice(next, equals);\n    if (separator.length === 0 || /[;,\\s]/.test(separator)) continue;\n\n    cookies.push(value.slice(start, index).trim());\n    start = next;\n    index = next - 1;\n  }\n\n  cookies.push(value.slice(start).trim());\n  return cookies.filter(Boolean);\n}\n\nexport function applyWebResponseHeaders(\n  res: Pick<ServerResponse, \"setHeader\"> & Partial<Pick<ServerResponse, \"getHeader\">>,\n  headers: Headers,\n  options: { appendSetCookie?: boolean } = {},\n): void {\n  const responseHeaders = headers as Headers & {\n    getSetCookie?: () => string[];\n    raw?: () => Record<string, string[]>;\n  };\n  const rawSetCookies = responseHeaders.raw?.()[\"set-cookie\"];\n  const setCookies = responseHeaders.getSetCookie?.() || rawSetCookies || [];\n  const existing =\n    options.appendSetCookie && typeof res.getHeader === \"function\"\n      ? res.getHeader(\"Set-Cookie\")\n      : undefined;\n  const existingCookies = Array.isArray(existing)\n    ? existing.map(String)\n    : existing === undefined\n      ? []\n      : [String(existing)];\n\n  let fallbackSetCookie = \"\";\n  headers.forEach((value, key) => {\n    if (key.toLowerCase() === \"set-cookie\") {\n      fallbackSetCookie = value;\n      return;\n    }\n    res.setHeader(key, value);\n  });\n\n  const cookies =\n    setCookies.length > 0\n      ? setCookies\n      : fallbackSetCookie\n        ? splitSetCookieHeader(fallbackSetCookie)\n        : [];\n  if (cookies.length > 0) {\n    res.setHeader(\"Set-Cookie\", [...existingCookies, ...cookies]);\n  }\n}\n\nexport async function sendWebResponse(res: ServerResponse, response: Response): Promise<void> {\n  res.statusCode = response.status;\n  applyWebResponseHeaders(res, response.headers, { appendSetCookie: true });\n\n  if (!response.body) {\n    res.end();\n    return;\n  }\n\n  if (typeof res.write !== \"function\") {\n    const body = await response.arrayBuffer();\n    res.end(Buffer.from(body));\n    return;\n  }\n\n  const reader = response.body.getReader();\n  const disconnectWatcher = watchResponseEvent(res, [\n    [\"close\", true],\n    [\"error\", true],\n  ]);\n\n  try {\n    while (true) {\n      if (res.destroyed) {\n        // The client disconnected mid-response; drop the rest of the body so\n        // the handler can return.\n        void reader.cancel().catch(() => {});\n        return;\n      }\n\n      const read = reader.read().then((result) => ({ type: \"read\" as const, result }));\n      const next = disconnectWatcher\n        ? await Promise.race([\n            read,\n            disconnectWatcher.promise.then(() => ({ type: \"disconnect\" as const })),\n          ])\n        : await read;\n      if (next.type === \"disconnect\") {\n        void reader.cancel().catch(() => {});\n        return;\n      }\n\n      const { done, value } = next.result;\n      if (done) {\n        break;\n      }\n\n      if (!value || value.byteLength === 0) {\n        continue;\n      }\n\n      if (!res.write(value)) {\n        if (!(await waitForWritable(res))) {\n          void reader.cancel().catch(() => {});\n          return;\n        }\n      }\n    }\n\n    res.end();\n  } catch (error) {\n    // Releasing the lock does not stop the producer. Cancel it when the\n    // downstream write fails, without waiting on app-owned cleanup or letting\n    // a cancellation failure replace the original error.\n    void reader.cancel(error).catch(() => {});\n    if (!res.writableEnded) {\n      const responseError = error instanceof Error ? error : new Error(String(error));\n      if (typeof res.destroy === \"function\") {\n        res.destroy(responseError);\n      } else {\n        res.end();\n      }\n    }\n    throw error;\n  } finally {\n    disconnectWatcher?.dispose();\n    try {\n      reader.releaseLock();\n    } catch {\n      // A disconnect can win the race with a pending read. Cancelling the\n      // reader settles it asynchronously, so there may be no lock to release\n      // synchronously here.\n    }\n  }\n}\n","import { assertBrowserStableRoutePath } from \"./routing/specificity\";\n\ninterface FarmNodeAbortRequest {\n  aborted?: boolean;\n  once(event: \"aborted\", listener: () => void): unknown;\n  off(event: \"aborted\", listener: () => void): unknown;\n}\n\ninterface FarmNodeAbortResponse {\n  writableEnded: boolean;\n  once(event: \"close\" | \"finish\", listener: () => void): unknown;\n  off(event: \"close\" | \"finish\", listener: () => void): unknown;\n}\n\n/** Share disconnect semantics between development and production Node requests. */\nexport function createFarmNodeRequestAbortSignal(\n  req: FarmNodeAbortRequest,\n  res: FarmNodeAbortResponse,\n): AbortSignal {\n  const controller = new AbortController();\n  let disposed = false;\n  const dispose = () => {\n    if (disposed) return;\n    disposed = true;\n    req.off(\"aborted\", abort);\n    res.off(\"close\", abortOnEarlyClose);\n    res.off(\"finish\", dispose);\n    controller.signal.removeEventListener(\"abort\", dispose);\n  };\n  const abort = () => controller.abort();\n  const abortOnEarlyClose = () => {\n    if (!res.writableEnded) abort();\n    dispose();\n  };\n\n  if (req.aborted) {\n    controller.abort();\n    return controller.signal;\n  }\n\n  req.once(\"aborted\", abort);\n  res.once(\"close\", abortOnEarlyClose);\n  res.once(\"finish\", dispose);\n  controller.signal.addEventListener(\"abort\", dispose, { once: true });\n  return controller.signal;\n}\n\nexport const DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 10_000_000;\nexport const DEFAULT_FARM_SERVER_HEADERS_TIMEOUT = 60_000;\nexport const DEFAULT_FARM_SERVER_REQUEST_TIMEOUT = 300_000;\nexport const DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT = 5_000;\nexport const DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT = 30_000;\nconst MAX_FARM_SERVER_TIMEOUT = 2_147_483_647;\n\nexport type FarmServerDuration = number | `${number}${\"ms\" | \"s\" | \"m\" | \"h\"}`;\n\nexport interface FarmServerHealthConfig {\n  /** Liveness endpoint. It remains healthy while a production process drains. */\n  livenessPath?: string;\n  /** Readiness endpoint. It returns 503 until startup completes and while draining. */\n  readinessPath?: string;\n}\n\nexport interface ResolvedFarmServerHealthConfig {\n  enabled: boolean;\n  livenessPath: string;\n  readinessPath: string;\n}\n\nexport interface FarmServerConfig {\n  /** Maximum request body size for API routes, integrations, workflows, and uploads. */\n  bodySizeLimit?: number | string;\n  /** Trust proxy-provided client address and request authority headers. Enable only behind a trusted proxy. */\n  trustProxy?: boolean;\n  /** Maximum time for a Node client to send complete request headers. */\n  headersTimeout?: FarmServerDuration;\n  /** Maximum time for a Node client to send the complete request. */\n  requestTimeout?: FarmServerDuration;\n  /** How long an idle Node keep-alive connection remains open after a response. */\n  keepAliveTimeout?: FarmServerDuration;\n  /** Maximum time the Node adapter drains traffic before forcing shutdown. */\n  gracefulShutdownTimeout?: FarmServerDuration;\n  /** Production liveness and readiness endpoints. Set to false to disable them. */\n  health?: false | FarmServerHealthConfig;\n}\n\nexport interface ResolvedFarmServerConfig {\n  bodySizeLimit: number;\n  trustProxy: boolean;\n  headersTimeout: number;\n  requestTimeout: number;\n  keepAliveTimeout: number;\n  gracefulShutdownTimeout: number;\n  health: ResolvedFarmServerHealthConfig;\n}\n\nexport type FarmRequestBodyErrorCode = \"BODY_TOO_LARGE\" | \"INVALID_CONTENT_LENGTH\";\n\n/** Apply the weak entity-tag comparison required by If-None-Match. */\nexport function matchesFarmIfNoneMatch(\n  value: string | readonly string[] | null | undefined,\n  etag: string,\n): boolean {\n  const expected = parseEntityTag(trimOptionalWhitespace(etag));\n  if (!expected) return false;\n\n  const values = Array.isArray(value) ? value : [value];\n  const combined = values\n    .filter((header): header is string => typeof header === \"string\")\n    .join(\",\");\n  const fieldValue = trimOptionalWhitespace(combined);\n  if (!fieldValue) return false;\n  if (fieldValue === \"*\") return true;\n\n  let matched = false;\n  let hasEntityTag = false;\n  for (const candidate of splitEntityTags(fieldValue)) {\n    const token = trimOptionalWhitespace(candidate);\n    if (!token) continue;\n\n    const parsed = parseEntityTag(token);\n    if (!parsed) return false;\n    hasEntityTag = true;\n    if (parsed === expected) matched = true;\n  }\n\n  return hasEntityTag && matched;\n}\n\nfunction trimOptionalWhitespace(value: string): string {\n  return value.replace(/^[\\t ]+|[\\t ]+$/g, \"\");\n}\n\nfunction parseEntityTag(value: string): string | null {\n  const opaqueTag = value.startsWith(\"W/\") ? value.slice(2) : value;\n  if (opaqueTag.length < 2 || opaqueTag[0] !== '\"' || opaqueTag.at(-1) !== '\"') return null;\n\n  for (let index = 1; index < opaqueTag.length - 1; index++) {\n    const code = opaqueTag.charCodeAt(index);\n    if (code === 0x21 || (code >= 0x23 && code <= 0x7e) || code >= 0x80) continue;\n    return null;\n  }\n\n  return opaqueTag;\n}\n\nfunction splitEntityTags(value: string): string[] {\n  const tags: string[] = [];\n  let start = 0;\n  let quoted = false;\n\n  for (let index = 0; index < value.length; index++) {\n    const character = value[index];\n    if (character === '\"') {\n      quoted = !quoted;\n    } else if (character === \",\" && !quoted) {\n      tags.push(value.slice(start, index));\n      start = index + 1;\n    }\n  }\n\n  tags.push(value.slice(start));\n  return tags;\n}\n\nexport class FarmRequestBodyError extends Error {\n  readonly code: FarmRequestBodyErrorCode;\n  readonly status: number;\n\n  constructor(code: FarmRequestBodyErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"FarmRequestBodyError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\nexport function resolveFarmServerConfig(\n  config: FarmServerConfig | ResolvedFarmServerConfig | undefined,\n): ResolvedFarmServerConfig {\n  const headersTimeout = parseFarmServerDuration(\n    config?.headersTimeout ?? DEFAULT_FARM_SERVER_HEADERS_TIMEOUT,\n    \"server.headersTimeout\",\n  );\n  const requestTimeout = parseFarmServerDuration(\n    config?.requestTimeout ?? DEFAULT_FARM_SERVER_REQUEST_TIMEOUT,\n    \"server.requestTimeout\",\n  );\n  if (headersTimeout > requestTimeout) {\n    throw new TypeError(\"server.headersTimeout must not exceed server.requestTimeout\");\n  }\n\n  return Object.freeze({\n    bodySizeLimit: parseBodySizeLimit(\n      config?.bodySizeLimit ?? DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n      \"server.bodySizeLimit\",\n    ),\n    trustProxy: config?.trustProxy === true,\n    headersTimeout,\n    requestTimeout,\n    keepAliveTimeout: parseFarmServerDuration(\n      config?.keepAliveTimeout ?? DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT,\n      \"server.keepAliveTimeout\",\n    ),\n    gracefulShutdownTimeout: parseFarmServerDuration(\n      config?.gracefulShutdownTimeout ?? DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,\n      \"server.gracefulShutdownTimeout\",\n    ),\n    health: resolveFarmServerHealthConfig(config?.health),\n  });\n}\n\nexport function parseFarmServerDuration(\n  value: FarmServerDuration,\n  optionName = \"duration\",\n): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    if (value > MAX_FARM_SERVER_TIMEOUT) {\n      throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be milliseconds or a duration such as \"30s\" or \"2m\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2];\n  const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n  const milliseconds = Math.floor(amount * multiplier);\n  if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n  if (milliseconds > MAX_FARM_SERVER_TIMEOUT) {\n    throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n  }\n  return milliseconds;\n}\n\nfunction resolveFarmServerHealthConfig(\n  config: false | FarmServerHealthConfig | ResolvedFarmServerHealthConfig | undefined,\n): ResolvedFarmServerHealthConfig {\n  if (config === false || (config && \"enabled\" in config && config.enabled === false)) {\n    return Object.freeze({\n      enabled: false,\n      livenessPath: \"/_farm/health/live\",\n      readinessPath: \"/_farm/health/ready\",\n    });\n  }\n\n  const livenessPath = normalizeHealthPath(\n    config?.livenessPath ?? \"/_farm/health/live\",\n    \"server.health.livenessPath\",\n  );\n  const readinessPath = normalizeHealthPath(\n    config?.readinessPath ?? \"/_farm/health/ready\",\n    \"server.health.readinessPath\",\n  );\n  if (livenessPath === readinessPath) {\n    throw new TypeError(\"server.health livenessPath and readinessPath must be different\");\n  }\n\n  return Object.freeze({ enabled: true, livenessPath, readinessPath });\n}\n\nfunction normalizeHealthPath(value: string, optionName: string): string {\n  const path = value.trim();\n  if (!path.startsWith(\"/\") || path.includes(\"?\") || path.includes(\"#\") || path.includes(\"*\")) {\n    throw new TypeError(`${optionName} must be an absolute pathname without a query or wildcard`);\n  }\n  const normalized = path.length > 1 ? path.replace(/\\/+$/, \"\") || \"/\" : path;\n  assertBrowserStableRoutePath(normalized);\n  return normalized;\n}\n\nexport function parseBodySizeLimit(value: number | string, optionName = \"bodySizeLimit\"): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)?$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be bytes or a size string such as \"500kb\" or \"10mb\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2] ?? \"b\";\n  const multiplier: Record<string, number> = {\n    b: 1,\n    kb: 1_000,\n    mb: 1_000_000,\n    gb: 1_000_000_000,\n    kib: 1_024,\n    mib: 1_048_576,\n    gib: 1_073_741_824,\n  };\n  const bytes = Math.floor(amount * multiplier[unit]);\n\n  if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n\n  return bytes;\n}\n\nexport async function bufferFarmRequestBody(request: Request, limit: number): Promise<Request> {\n  if (request.method === \"GET\" || request.method === \"HEAD\" || request.body === null) {\n    return request;\n  }\n\n  const bytes = await readFarmRequestBody(request, limit);\n  const body = new Uint8Array(bytes.byteLength);\n  body.set(bytes);\n  return new Request(request, {\n    // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.\n    body: body.buffer,\n  });\n}\n\nexport async function readFarmRequestBody(request: Request, limit: number): Promise<Uint8Array> {\n  try {\n    validateContentLength(request.headers.get(\"content-length\"), limit);\n  } catch (error) {\n    // A cloned Request is a tee branch: its cancellation may wait for the\n    // untouched branch. Rejection must not wait for producer-owned cleanup.\n    void request.body?.cancel(error).catch(() => {});\n    throw error;\n  }\n  throwIfAborted(request.signal);\n  if (!request.body) return new Uint8Array();\n\n  const reader = request.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  const cancelBodyRead = () => {\n    void reader.cancel(request.signal.reason).catch(() => {});\n  };\n  request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n  try {\n    while (true) {\n      throwIfAborted(request.signal);\n      const { done, value } = await reader.read();\n      // Cancellation resolves a pending read as EOF, not necessarily an error.\n      throwIfAborted(request.signal);\n      if (done) break;\n      if (!value) continue;\n\n      total += value.byteLength;\n      if (total > limit) {\n        const error = new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } catch (error) {\n    if (request.signal.aborted) throwIfAborted(request.signal);\n    throw error;\n  } finally {\n    request.signal.removeEventListener(\"abort\", cancelBodyRead);\n    reader.releaseLock();\n  }\n\n  const body = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    body.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return body;\n}\n\nexport async function readNodeRequestBody(\n  request: {\n    headers: Record<string, string | string[] | undefined>;\n    on(event: \"data\", listener: (chunk: unknown) => void): unknown;\n    on(event: \"end\", listener: () => void): unknown;\n    on(event: \"error\", listener: (error: Error) => void): unknown;\n    removeListener?(event: string, listener: (...args: any[]) => void): unknown;\n    resume?(): unknown;\n  },\n  limit: number,\n): Promise<Buffer> {\n  const rawContentLength = request.headers[\"content-length\"];\n  const contentLength = Array.isArray(rawContentLength) ? rawContentLength[0] : rawContentLength;\n  try {\n    validateContentLength(contentLength, limit);\n  } catch (error) {\n    request.resume?.();\n    throw error;\n  }\n\n  return await new Promise<Buffer>((resolve, reject) => {\n    const chunks: Buffer[] = [];\n    let total = 0;\n    let settled = false;\n\n    const cleanup = () => {\n      request.removeListener?.(\"data\", onData);\n      request.removeListener?.(\"end\", onEnd);\n      request.removeListener?.(\"error\", onError);\n    };\n    const rejectOnce = (error: Error) => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      request.resume?.();\n      reject(error);\n    };\n    const onData = (chunk: unknown) => {\n      const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as any);\n      total += bytes.byteLength;\n      if (total > limit) {\n        rejectOnce(new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\"));\n        return;\n      }\n      chunks.push(bytes);\n    };\n    const onEnd = () => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      resolve(Buffer.concat(chunks, total));\n    };\n    const onError = (error: Error) => rejectOnce(error);\n\n    request.on(\"data\", onData);\n    request.on(\"end\", onEnd);\n    request.on(\"error\", onError);\n  });\n}\n\nexport function createFarmRequestBodyErrorResponse(error: unknown): Response | null {\n  if (!(error instanceof FarmRequestBodyError)) return null;\n\n  return new Response(error.status === 413 ? \"Payload Too Large\" : \"Bad Request\", {\n    status: error.status,\n    headers: {\n      \"cache-control\": \"no-store\",\n      \"content-type\": \"text/plain; charset=utf-8\",\n      \"x-content-type-options\": \"nosniff\",\n    },\n  });\n}\n\nfunction validateContentLength(value: string | null | undefined, limit: number): void {\n  const contentLength = value?.trim();\n  if (!contentLength) return;\n  if (!/^\\d+$/.test(contentLength)) {\n    throw new FarmRequestBodyError(\"INVALID_CONTENT_LENGTH\", 400, \"Invalid content-length header\");\n  }\n  if (Number(contentLength) > limit) {\n    throw new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (!signal.aborted) return;\n  if (signal.reason !== undefined) throw signal.reason;\n  throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import { 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","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","import type { RouteSegment, ParsedRoute } from \"./types\";\nimport path from \"path\";\nimport {\n  assertBrowserStableRoutePath,\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n} from \"./routing/specificity\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { decodeRouteSegment } from \"./utils/decode\";\n\nexport function parseRoutePath(filePath: string): ParsedRoute {\n  const segments: RouteSegment[] = [];\n  const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n  const pathParts = normalizedPath.split(\"/\").filter(Boolean);\n\n  const fileName = pathParts.pop() || \"\";\n  const fileType = getRouteType(fileName);\n  const routePath = `/${pathParts.join(\"/\")}`;\n  assertBrowserStableRoutePath(routePath);\n  assertTerminalCatchAll(routePath);\n  assertUniqueRouteParameters(routePath);\n\n  for (const part of pathParts) {\n    // Route groups like `(marketing)` organize files without adding URL\n    // segments. Mirrors isRouteGroup in router.ts for programmatic routes.\n    if (part.startsWith(\"(\") && part.endsWith(\")\")) continue;\n    if (part.startsWith(\"[\") && part.endsWith(\"]\")) {\n      let segment = part.slice(1, -1);\n      const isDynamic = true;\n      let isOptional = false;\n      let isCatchAll = false;\n\n      if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n        isOptional = true;\n        segment = segment.slice(1, -1);\n        if (segment.startsWith(\"...\")) {\n          segment = segment.slice(3);\n          isCatchAll = true;\n        }\n      } else if (segment.startsWith(\"...\")) {\n        segment = segment.slice(3);\n        isCatchAll = true;\n      }\n\n      segments.push({ segment, isDynamic, isOptional, isCatchAll });\n    } else {\n      segments.push({\n        segment: part,\n        isDynamic: false,\n        isOptional: false,\n        isCatchAll: false,\n      });\n    }\n  }\n\n  return {\n    segments,\n    filePath: normalizedPath,\n    type: fileType,\n  };\n}\n\nfunction getRouteType(fileName: string): ParsedRoute[\"type\"] {\n  const baseName = fileName.replace(/\\.(tsx?|jsx?|vue|svelte|mdx?|markdown)$/, \"\");\n\n  switch (baseName) {\n    case \"page\":\n      return \"page\";\n    case \"layout\":\n      return \"layout\";\n    case \"loading\":\n      return \"loading\";\n    case \"error\":\n      return \"error\";\n    case \"not-found\":\n      return \"not-found\";\n    default:\n      return \"page\";\n  }\n}\n\nexport function segmentsToPattern(segments: RouteSegment[]): string {\n  if (segments.length === 0) return \"/\";\n\n  return (\n    \"/\" +\n    segments\n      .map((segment) => {\n        if (!segment.isDynamic) return segment.segment;\n\n        if (segment.isCatchAll) {\n          return segment.isOptional ? `*${segment.segment}?` : `*${segment.segment}`;\n        }\n\n        return `:${segment.segment}`;\n      })\n      .join(\"/\")\n  );\n}\n\nexport function matchRoute(\n  url: string,\n  segments: RouteSegment[],\n): { params: Record<string, string>; matches: boolean } {\n  const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n  const params: Record<string, string> = {};\n  if (segments.length === 0) {\n    return { params, matches: urlParts.length === 0 };\n  }\n\n  let urlIndex = 0;\n  let segmentIndex = 0;\n\n  while (segmentIndex < segments.length && urlIndex <= urlParts.length) {\n    const segment = segments[segmentIndex];\n\n    if (!segment.isDynamic) {\n      if (urlParts[urlIndex] !== segment.segment) {\n        return { params: {}, matches: false };\n      }\n      urlIndex++;\n      segmentIndex++;\n    } else if (segment.isCatchAll) {\n      const remainingParts = urlParts.slice(urlIndex);\n\n      if (remainingParts.length === 0 && !segment.isOptional) {\n        return { params: {}, matches: false };\n      }\n\n      params[segment.segment] = remainingParts.join(\"/\");\n      urlIndex = urlParts.length;\n      segmentIndex++;\n    } else {\n      if (urlIndex >= urlParts.length) {\n        return { params: {}, matches: false };\n      }\n\n      params[segment.segment] = urlParts[urlIndex];\n      urlIndex++;\n      segmentIndex++;\n    }\n  }\n\n  const matches = segmentIndex === segments.length && urlIndex === urlParts.length;\n\n  return { params, matches };\n}\n\n/** Match a route segment chain as an owner of the pathname or one of its descendants. */\nexport function matchRoutePrefix(url: string, segments: RouteSegment[]): boolean {\n  const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n  let urlIndex = 0;\n\n  for (const segment of segments) {\n    if (segment.isCatchAll) {\n      return segment.isOptional || urlIndex < urlParts.length;\n    }\n\n    const urlPart = urlParts[urlIndex];\n    if (urlPart === undefined) return false;\n    if (!segment.isDynamic && segment.segment !== urlPart) return false;\n    urlIndex++;\n  }\n\n  return true;\n}\n\nexport function resolveAppPath(root: string, ...paths: string[]): string {\n  return path.resolve(root, ...paths);\n}\n\n/**\n * Convert an absolute module path inside the project root to a root-relative\n * URL path with forward slashes (e.g. `/src/app/page.tsx`), for values the\n * client passes to dynamic `import()`. On Windows the naive root-prefix slice\n * yields `\\src\\app\\page.tsx`, which is not a valid module specifier. Returns\n * undefined for paths outside the root so callers keep their own fallbacks.\n */\nexport function toRootRelativeUrlPath(\n  absolutePath: string,\n  projectRoot: string,\n): string | undefined {\n  if (absolutePath === projectRoot) return \"\";\n  if (absolutePath.startsWith(`${projectRoot}/`) || absolutePath.startsWith(`${projectRoot}\\\\`)) {\n    return absolutePath.slice(projectRoot.length).replace(/\\\\/g, \"/\");\n  }\n  return undefined;\n}\n\n/**\n * Normalize a filesystem path to forward slashes. Node's fs accepts these on\n * every platform, and module ids handed to bundlers (e.g. Nitro handler and\n * task entries) must not contain backslashes.\n */\nexport function toPosixPath(filePath: string): string {\n  return filePath.replace(/\\\\/g, \"/\");\n}\n\nexport function toViteModuleId(filePath: string, root: string): string {\n  if (!path.isAbsolute(filePath)) return filePath;\n\n  const relativePath = path.relative(root, filePath);\n  if (relativePath && !relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath)) {\n    return `/${relativePath.split(path.sep).join(\"/\")}`;\n  }\n\n  const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n  return normalizedPath.startsWith(\"/\") ? `/@fs${normalizedPath}` : `/@fs/${normalizedPath}`;\n}\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n  try {\n    const fs = await import(\"fs/promises\");\n    await fs.access(filePath);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function globFiles(pattern: string, cwd: string): Promise<string[]> {\n  const glob = await import(\"fast-glob\");\n  return glob.default(pattern, { cwd, absolute: false });\n}\n\nexport function parseSearchParams(\n  searchParams: URLSearchParams,\n): Record<string, string | string[]> {\n  return searchParamsToObject(searchParams) as Record<string, string | string[]>;\n}\n\nexport const logger = {\n  info: (message: string) => console.log(`[info] ${message}`),\n  success: (message: string) => console.log(`[success] ${message}`),\n  warn: (message: string) => console.warn(`⚠️  ${message}`),\n  error: (message: string) => console.error(`❌ ${message}`),\n  ready: (message: string) => console.log(`${message}`),\n  event: (message: string) => console.log(`  ${message}`),\n};\n","import {\n  createFarmRequestBodyErrorResponse,\n  readFarmRequestBody,\n  resolveFarmServerConfig,\n  type FarmServerConfig,\n  type ResolvedFarmServerConfig,\n} from \"./server-http\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { farmSecretsMatch } from \"./secret-compare\";\nimport { isFarmDeployedRuntime, readFarmEnvironmentValue } from \"./utils/runtime-env\";\nimport { decodeRouteSegment } from \"./utils/decode\";\nimport { toPosixPath } from \"./utils\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport {\n  isAbsolute as isAbsolutePath,\n  normalize as normalizePath,\n  relative as relativeFilePath,\n  resolve as resolvePath,\n  sep as pathSeparator,\n} from \"node:path\";\n\nexport type FarmWorkflowSchedule = string | string[];\n\nexport interface FarmWorkflowsUserConfig {\n  /** Enable or disable Farm workflow discovery. Enabled by default. */\n  enabled?: boolean;\n  /** Directory or directories to scan for workflow modules. */\n  dir?: string | string[];\n  /** Alias for dir. */\n  dirs?: string[];\n  /** HTTP route used for manual and URL-based cron invocation. */\n  route?: string;\n  /** Environment variable that stores the optional runner secret. */\n  secretEnv?: string;\n  /** Inline runner secret. Prefer secretEnv for deployed apps. */\n  secret?: string;\n  /**\n   * Serve the workflow route without a secret in a deployed runtime.\n   * Defaults to false: without a secret the route is public, so production\n   * requests are rejected unless this is explicitly enabled.\n   */\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmWorkflowsResolvedConfig {\n  enabled: boolean;\n  dirs: string[];\n  route: string;\n  secretEnv: string;\n  secret?: string;\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmWorkflowLogger {\n  info: (...args: unknown[]) => void;\n  warn: (...args: unknown[]) => void;\n  error: (...args: unknown[]) => void;\n}\n\nexport interface FarmWorkflowRunContext<TPayload = unknown> {\n  id: string;\n  name: string;\n  payload: TPayload;\n  scheduledTime?: number | string;\n  request?: Request;\n  event?: unknown;\n  env: Record<string, string | undefined>;\n  data: Map<string, unknown>;\n  log: FarmWorkflowLogger;\n}\n\nexport interface FarmWorkflowDefinition<TPayload = unknown, TResult = unknown> {\n  kind?: \"farm-workflow\";\n  id?: string;\n  description?: string;\n  schedule?: FarmWorkflowSchedule;\n  timezone?: string;\n  run: (ctx: FarmWorkflowRunContext<TPayload>) => TResult | Promise<TResult>;\n}\n\nexport interface FarmCronDefinition<\n  TPayload = unknown,\n  TResult = unknown,\n> extends FarmWorkflowDefinition<TPayload, TResult> {\n  schedule: FarmWorkflowSchedule;\n}\n\nexport interface FarmDiscoveredWorkflow {\n  id: string;\n  filePath: string;\n  description?: string;\n  schedule: string[];\n  timezone?: string;\n  routePath: string;\n}\n\nexport interface PreparedFarmWorkflows {\n  workflows: FarmDiscoveredWorkflow[];\n  tasks: Record<string, { handler: string; description: string }>;\n  scheduledTasks: Record<string, string | string[]>;\n  handlerPath?: string;\n  manifestPath?: string;\n}\n\nexport interface FarmWorkflowHTTPHandlerOptions {\n  workflows: FarmDiscoveredWorkflow[];\n  config: FarmWorkflowsResolvedConfig;\n  loadModule: (workflow: FarmDiscoveredWorkflow) => Promise<Record<string, any>>;\n  server?: FarmServerConfig | ResolvedFarmServerConfig;\n}\n\nexport const DEFAULT_FARM_WORKFLOW_DIRS = [\"src/jobs\", \"src/workflows\", \"src/cron\"];\nexport const DEFAULT_FARM_WORKFLOW_ROUTE = \"/api/_farm/workflows\";\nexport const DEFAULT_FARM_WORKFLOW_SECRET_ENV = \"CRON_SECRET\";\nconst MISSING_FARM_WORKFLOW_SECRET_ERROR =\n  \"Workflow route requires a secret. Set the CRON_SECRET environment variable, configure workflows.secret, or set workflows.allowUnsecured to true.\";\n\nexport function defineWorkflow<const TPayload = unknown, TResult = unknown>(\n  definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n  return {\n    ...definition,\n    kind: \"farm-workflow\",\n  };\n}\n\nexport function defineTask<const TPayload = unknown, TResult = unknown>(\n  definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n  return defineWorkflow(definition);\n}\n\n/**\n * @deprecated Configure `cron` in `farm.config.ts` and point it at an API route.\n */\nexport function defineCron<const TPayload = unknown, TResult = unknown>(\n  definition: FarmCronDefinition<TPayload, TResult>,\n): FarmCronDefinition<TPayload, TResult> {\n  return {\n    ...definition,\n    kind: \"farm-workflow\",\n  };\n}\n\nexport function resolveWorkflowsConfig(\n  workflows: FarmWorkflowsUserConfig | boolean | undefined,\n): FarmWorkflowsResolvedConfig {\n  if (workflows === false) {\n    return {\n      enabled: false,\n      dirs: [...DEFAULT_FARM_WORKFLOW_DIRS],\n      route: DEFAULT_FARM_WORKFLOW_ROUTE,\n      secretEnv: DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n    };\n  }\n\n  const options = workflows && typeof workflows === \"object\" ? workflows : {};\n  const dirs = normalizeWorkflowDirs(options);\n\n  return {\n    enabled: options.enabled ?? true,\n    dirs,\n    route: normalizeWorkflowRoute(options.route || DEFAULT_FARM_WORKFLOW_ROUTE),\n    secretEnv: options.secretEnv || DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n    secret: options.secret,\n    allowUnsecured: options.allowUnsecured === true,\n  };\n}\n\nexport async function discoverFarmWorkflows(\n  config: {\n    root?: string;\n    workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean;\n  },\n  options: {\n    loadModule?: (filePath: string) => Promise<Record<string, any>>;\n  } = {},\n): Promise<FarmDiscoveredWorkflow[]> {\n  const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n    ? config.workflows\n    : resolveWorkflowsConfig(config.workflows);\n  if (!workflowConfig.enabled) return [];\n\n  const root = config.root || process.cwd();\n  const files = await findWorkflowFiles(root, workflowConfig.dirs);\n  const workflows: FarmDiscoveredWorkflow[] = [];\n  const seenIds = new Map<string, string>();\n\n  for (const filePath of files) {\n    const module = options.loadModule\n      ? await options.loadModule(filePath)\n      : await loadWorkflowModule(filePath, root);\n    const definition = resolveWorkflowDefinition(module);\n    if (!definition) continue;\n\n    const id = normalizeWorkflowId(\n      definition.id || workflowIdFromFile(root, workflowConfig.dirs, filePath),\n    );\n    const previousPath = seenIds.get(id);\n    if (previousPath) {\n      throw new Error(\n        `Duplicate Farm workflow id \"${id}\" found in ${relativePath(root, previousPath)} and ${relativePath(root, filePath)}.`,\n      );\n    }\n    seenIds.set(id, filePath);\n\n    workflows.push({\n      id,\n      filePath,\n      description: definition.description,\n      schedule: normalizeSchedule(definition.schedule),\n      timezone: definition.timezone,\n      routePath: joinRoute(workflowConfig.route, encodeURIComponent(id)),\n    });\n  }\n\n  return workflows;\n}\n\nexport function createFarmWorkflowRequestHandler(options: FarmWorkflowHTTPHandlerOptions) {\n  const workflowsById = new Map(options.workflows.map((workflow) => [workflow.id, workflow]));\n\n  return async function handleFarmWorkflowRequest(request: Request): Promise<Response | null> {\n    const url = new URL(request.url);\n    const route = normalizeWorkflowRoute(options.config.route);\n    if (url.pathname !== route && !url.pathname.startsWith(`${route}/`)) {\n      return null;\n    }\n\n    if (url.pathname === route) {\n      const secretError = verifyWorkflowSecret(request, options.config);\n      if (secretError) return secretError;\n\n      return Response.json({\n        workflows: options.workflows.map(toWorkflowMetadata),\n      });\n    }\n\n    const id = decodeRouteSegment(url.pathname.slice(route.length + 1));\n\n    // Verify the secret before consulting the workflow id map so the\n    // existing-vs-missing distinction is not disclosed to callers without\n    // the secret (a 401 for unknown ids would otherwise become a 404 oracle).\n    const secretError = verifyWorkflowSecret(request, options.config);\n    if (secretError) return secretError;\n\n    const workflow = workflowsById.get(id);\n    if (!workflow) {\n      return Response.json({ error: `Workflow \"${id}\" was not found.` }, { status: 404 });\n    }\n\n    let payload: unknown;\n    try {\n      payload = await readWorkflowPayload(\n        request,\n        resolveFarmServerConfig(options.server).bodySizeLimit,\n      );\n    } catch (error) {\n      const response = createFarmRequestBodyErrorResponse(error);\n      if (response) return response;\n      if (error instanceof SyntaxError) {\n        return Response.json({ error: \"Invalid workflow request body.\" }, { status: 400 });\n      }\n      throw error;\n    }\n    const module = await options.loadModule(workflow);\n    const result = await runFarmWorkflowModule(module, {\n      id: workflow.id,\n      name: workflow.id,\n      payload,\n      request,\n      scheduledTime: readScheduledTime(payload),\n    });\n\n    return Response.json({\n      id: workflow.id,\n      ok: true,\n      result: result ?? null,\n    });\n  };\n}\n\nexport async function runFarmWorkflowModule(\n  module: Record<string, any>,\n  context: {\n    id: string;\n    name?: string;\n    payload?: unknown;\n    scheduledTime?: number | string;\n    request?: Request;\n    event?: unknown;\n    env?: Record<string, string | undefined>;\n  },\n): Promise<unknown> {\n  const definition = resolveWorkflowDefinition(module);\n  if (!definition) {\n    throw new Error(`Farm workflow \"${context.id}\" does not export a workflow definition.`);\n  }\n\n  return await definition.run({\n    id: context.id,\n    name: context.name || context.id,\n    payload: context.payload,\n    scheduledTime: context.scheduledTime,\n    request: context.request,\n    event: context.event,\n    env: context.env || process.env,\n    data: new Map<string, unknown>(),\n    log: console,\n  });\n}\n\nexport async function prepareFarmWorkflowsForNitro(config: {\n  root?: string;\n  distDir?: string;\n  workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean;\n  server?: FarmServerConfig | ResolvedFarmServerConfig;\n}): Promise<PreparedFarmWorkflows> {\n  const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n    ? config.workflows\n    : resolveWorkflowsConfig(config.workflows);\n  const root = config.root || process.cwd();\n  const distDir = config.distDir || \".farm\";\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const generatedDir = path.join(root, distDir, \".nitro\", \"farm-workflows\");\n  const workflows = await discoverFarmWorkflows({\n    root,\n    workflows: workflowConfig,\n  });\n\n  if (workflows.length === 0) {\n    await fs.rm(generatedDir, { recursive: true, force: true });\n    return {\n      workflows,\n      tasks: {},\n      scheduledTasks: {},\n    };\n  }\n\n  await fs.rm(generatedDir, { recursive: true, force: true });\n  await fs.mkdir(generatedDir, { recursive: true });\n\n  const tasks: PreparedFarmWorkflows[\"tasks\"] = {};\n  const scheduledTasks = createScheduledTasks(workflows);\n\n  const wrapperNames = resolveWorkflowWrapperFileNames(workflows.map((workflow) => workflow.id));\n  for (const workflow of workflows) {\n    const wrapperPath = toPosixPath(\n      path.join(generatedDir, `${wrapperNames.get(workflow.id)}.mjs`),\n    );\n    await fs.writeFile(wrapperPath, createNitroTaskWrapper(workflow), \"utf8\");\n    tasks[workflow.id] = {\n      handler: wrapperPath,\n      description: workflow.description || `Farm workflow ${workflow.id}`,\n    };\n  }\n\n  const handlerPath = toPosixPath(path.join(generatedDir, \"http-handler.mjs\"));\n  await fs.writeFile(\n    handlerPath,\n    createNitroWorkflowHTTPHandler(\n      workflowConfig,\n      workflows,\n      resolveFarmServerConfig(config.server),\n    ),\n    \"utf8\",\n  );\n\n  const manifestPath = path.join(generatedDir, \"manifest.json\");\n  await fs.writeFile(\n    manifestPath,\n    JSON.stringify(\n      {\n        route: workflowConfig.route,\n        secretEnv: workflowConfig.secretEnv,\n        trigger: {\n          method: \"GET\",\n          authorization: `Bearer $${workflowConfig.secretEnv}`,\n        },\n        workflows: workflows.map(toWorkflowMetadata),\n      },\n      null,\n      2,\n    ),\n    \"utf8\",\n  );\n\n  return {\n    workflows,\n    tasks,\n    scheduledTasks,\n    handlerPath,\n    manifestPath,\n  };\n}\n\nexport function createFarmWorkflowVercelCrons(\n  workflows: FarmDiscoveredWorkflow[],\n): Array<{ path: string; schedule: string }> {\n  return workflows.flatMap((workflow) =>\n    workflow.schedule.map((schedule) => ({\n      path: workflow.routePath,\n      schedule,\n    })),\n  );\n}\n\nexport function applyFarmWorkflowVercelCrons(\n  vercelConfig: Record<string, any>,\n  workflows: FarmDiscoveredWorkflow[],\n): Record<string, any> {\n  const crons = createFarmWorkflowVercelCrons(workflows);\n  if (crons.length === 0) return vercelConfig;\n\n  const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n  const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n  const nextCrons = [...existingCrons];\n  for (const cron of crons) {\n    const key = `${cron.path}:${cron.schedule}`;\n    if (seen.has(key)) continue;\n    seen.add(key);\n    nextCrons.push(cron);\n  }\n  return {\n    ...vercelConfig,\n    crons: nextCrons,\n  };\n}\n\nfunction isResolvedWorkflowConfig(value: unknown): value is FarmWorkflowsResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"dirs\" in value &&\n    Array.isArray((value as FarmWorkflowsResolvedConfig).dirs) &&\n    typeof (value as FarmWorkflowsResolvedConfig).route === \"string\"\n  );\n}\n\nfunction normalizeWorkflowDirs(options: FarmWorkflowsUserConfig): string[] {\n  const rawDirs =\n    options.dirs ||\n    (Array.isArray(options.dir) ? options.dir : options.dir ? [options.dir] : undefined);\n  const dirs = rawDirs && rawDirs.length > 0 ? rawDirs : DEFAULT_FARM_WORKFLOW_DIRS;\n  return [...new Set(dirs.map(normalizeWorkflowDir).filter(Boolean))];\n}\n\nfunction normalizeWorkflowDir(value: string): string {\n  const dir = value.trim();\n  if (!dir) return \"\";\n  return isAbsolutePath(dir) ? normalizePath(dir) : trimSlashes(dir);\n}\n\nfunction normalizeWorkflowRoute(route: string): string {\n  const trimmed = route.trim();\n  if (!trimmed || trimmed === \"/\") return DEFAULT_FARM_WORKFLOW_ROUTE;\n  const normalized = `/${trimSlashes(trimmed)}`;\n  validateConfigRouteSource(normalized, \"workflows.route\");\n  return normalized;\n}\n\nfunction normalizeWorkflowId(id: string): string {\n  const normalized = id\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\.(tsx?|jsx?|mjs|cjs)$/, \"\")\n    .replace(/\\/index$/, \"\")\n    .replace(/[^a-zA-Z0-9._/-]+/g, \"-\")\n    .replace(/^\\/+|\\/+$/g, \"\")\n    .replace(/\\/+/g, \"/\");\n  return normalized || \"workflow\";\n}\n\nfunction normalizeSchedule(schedule: FarmWorkflowSchedule | undefined): string[] {\n  if (!schedule) return [];\n  return (Array.isArray(schedule) ? schedule : [schedule])\n    .map((value) => value.trim())\n    .filter(Boolean);\n}\n\nfunction resolveWorkflowDefinition(\n  module: Record<string, any>,\n): FarmWorkflowDefinition | FarmCronDefinition | null {\n  const candidates = [module.default, module.workflow, module.cron, module.task, module.job];\n  for (const candidate of candidates) {\n    if (candidate && typeof candidate === \"object\" && typeof candidate.run === \"function\") {\n      return candidate as FarmWorkflowDefinition;\n    }\n  }\n  return null;\n}\n\nasync function findWorkflowFiles(root: string, dirs: string[]): Promise<string[]> {\n  const path = await import(\"path\");\n  const files: string[] = [];\n\n  for (const dir of dirs) {\n    const absoluteDir = path.isAbsolute(dir) ? dir : path.join(root, dir);\n    if (!(await pathExists(absoluteDir))) continue;\n    await walkWorkflowDir(absoluteDir, files);\n  }\n\n  return files.sort();\n}\n\nasync function walkWorkflowDir(dir: string, files: string[]): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const entries = await fs.readdir(dir, { withFileTypes: true });\n  for (const entry of entries) {\n    const filePath = path.join(dir, entry.name);\n    if (entry.isDirectory()) {\n      if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n      await walkWorkflowDir(filePath, files);\n      continue;\n    }\n    if (isWorkflowFile(entry.name)) {\n      files.push(filePath);\n    }\n  }\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n  const fs = await import(\"fs/promises\");\n  return fs\n    .access(filePath)\n    .then(() => true)\n    .catch(() => false);\n}\n\nfunction isWorkflowFile(fileName: string): boolean {\n  return /\\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(fileName) && !/\\.d\\.[cm]?ts$/.test(fileName);\n}\n\nasync function loadWorkflowModule(filePath: string, root: string): Promise<Record<string, any>> {\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const { pathToFileURL } = await import(\"url\");\n  const { build } = await import(\"esbuild\");\n  const outDir = path.join(root, \".farm\", \".workflow-loader\");\n  await fs.mkdir(outDir, { recursive: true });\n  const outfile = path.join(\n    outDir,\n    `workflow-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n  );\n\n  await build({\n    absWorkingDir: root,\n    entryPoints: [filePath],\n    outfile,\n    bundle: true,\n    format: \"esm\",\n    platform: \"node\",\n    target: `node${process.versions.node.split(\".\")[0]}`,\n    packages: \"external\",\n    external: [\"@farm.js/core\", \"@farm.js/core/*\", \"nitro\", \"nitro/*\"],\n    jsx: \"automatic\",\n    logLevel: \"silent\",\n    sourcemap: \"inline\",\n  });\n\n  try {\n    return await import(/* @vite-ignore */ `${pathToFileURL(outfile).href}?t=${Date.now()}`);\n  } finally {\n    await fs.unlink(outfile).catch(() => undefined);\n  }\n}\n\nfunction workflowIdFromFile(root: string, dirs: string[], filePath: string): string {\n  for (const dir of dirs) {\n    const scanRoot = isAbsolutePath(dir) ? dir : resolvePath(root, dir);\n    const candidate = relativeFilePath(scanRoot, filePath);\n    if (candidate && candidate !== \"..\" && !candidate.startsWith(`..${pathSeparator}`)) {\n      return normalizeWorkflowId(candidate);\n    }\n  }\n\n  return normalizeWorkflowId(relativeFilePath(root, filePath));\n}\n\nfunction createScheduledTasks(\n  workflows: FarmDiscoveredWorkflow[],\n): Record<string, string | string[]> {\n  const scheduleMap = new Map<string, string[]>();\n  for (const workflow of workflows) {\n    for (const schedule of workflow.schedule) {\n      const taskIds = scheduleMap.get(schedule) || [];\n      taskIds.push(workflow.id);\n      scheduleMap.set(schedule, taskIds);\n    }\n  }\n\n  return Object.fromEntries(\n    [...scheduleMap.entries()].map(([schedule, taskIds]) => [\n      schedule,\n      taskIds.length === 1 ? taskIds[0] : taskIds,\n    ]),\n  );\n}\n\nfunction createNitroTaskWrapper(workflow: FarmDiscoveredWorkflow): string {\n  const normalizedPath = workflow.filePath.replace(/\\\\/g, \"/\");\n  return `\nimport { defineTask } from \"nitro/runtime\";\nimport { runFarmWorkflowModule } from \"@farm.js/core/workflows\";\nimport * as workflowModule from ${JSON.stringify(normalizedPath)};\n\nexport default defineTask({\n  meta: {\n    description: ${JSON.stringify(workflow.description || `Farm workflow ${workflow.id}`)}\n  },\n  async run(event) {\n    const payload = event?.payload || {};\n    const env = event?.context?.cloudflare?.env || event?.context?.env || process.env;\n    return await runFarmWorkflowModule(workflowModule, {\n      id: ${JSON.stringify(workflow.id)},\n      name: event?.name || ${JSON.stringify(workflow.id)},\n      payload,\n      scheduledTime: payload.scheduledTime,\n      request: event?.context?.request,\n      event,\n      env\n    });\n  }\n});\n`.trim();\n}\n\nfunction createNitroWorkflowHTTPHandler(\n  config: FarmWorkflowsResolvedConfig,\n  workflows: FarmDiscoveredWorkflow[],\n  server: ResolvedFarmServerConfig,\n): string {\n  return `\nimport { H3 } from \"h3\";\nimport { runTask } from \"nitro/runtime\";\nimport {\n  createFarmRequestBodyErrorResponse,\n  farmSecretsMatch,\n  readFarmRequestBody,\n  searchParamsToObject\n} from \"@farm.js/core/internal/production-runtime\";\n\nconst route = ${JSON.stringify(config.route)};\nconst secretEnv = ${JSON.stringify(config.secretEnv)};\nconst inlineSecret = ${JSON.stringify(config.secret || \"\")};\nconst allowUnsecured = ${JSON.stringify(config.allowUnsecured === true)};\nconst bodySizeLimit = ${JSON.stringify(server.bodySizeLimit)};\nconst workflows = ${JSON.stringify(workflows.map(toWorkflowMetadata))};\nconst workflowIds = new Set(workflows.map((workflow) => workflow.id));\n\nfunction json(value, status = 200) {\n  return new Response(JSON.stringify(value), {\n    status,\n    headers: { \"content-type\": \"application/json\" }\n  });\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction getHeader(event, name) {\n  return event.req.headers.get(name);\n}\n\nfunction getSecret() {\n  // Match the dev-path verifyWorkflowSecret's resolution (readFarmEnvironmentValue):\n  // runtime bindings on globalThis.__env__ first, then process.env. Reading\n  // process.env alone misses a Cloudflare Workers secret, so a correctly\n  // configured deployment would see no secret and reject every request with 401.\n  const runtimeBindings = globalThis.__env__;\n  const runtimeSecret =\n    runtimeBindings && typeof runtimeBindings === \"object\" ? runtimeBindings[secretEnv] : undefined;\n  const resolved =\n    typeof runtimeSecret === \"string\"\n      ? runtimeSecret\n      : typeof process !== \"undefined\"\n        ? process.env?.[secretEnv]\n        : undefined;\n  return inlineSecret || resolved || \"\";\n}\n\nfunction verifySecret(event) {\n  const secret = getSecret();\n  if (!secret) {\n    if (allowUnsecured) return null;\n    return json({ error: ${JSON.stringify(MISSING_FARM_WORKFLOW_SECRET_ERROR)} }, 401);\n  }\n  const authorization = getHeader(event, \"authorization\") || \"\";\n  const headerSecret = getHeader(event, \"x-farm-workflow-secret\") || \"\";\n  const bearer = authorization.match(/^Bearer\\\\s+(.+)$/i)?.[1] || \"\";\n  if (farmSecretsMatch(headerSecret, secret) || farmSecretsMatch(bearer, secret)) return null;\n  return json({ error: \"Unauthorized workflow request.\" }, 401);\n}\n\nasync function readPayload(event) {\n  if (event.req.method === \"GET\" || event.req.method === \"HEAD\") {\n    return searchParamsToObject(event.url.searchParams);\n  }\n  const bytes = await readFarmRequestBody(event.req, bodySizeLimit);\n  const text = new TextDecoder().decode(bytes);\n  if (!text) return {};\n  const contentType = (getHeader(event, \"content-type\") || \"\").split(\";\", 1)[0].trim().toLowerCase();\n  if (\n    contentType === \"application/json\" ||\n    (contentType.startsWith(\"application/\") && contentType.endsWith(\"+json\"))\n  ) {\n    return JSON.parse(text);\n  }\n  return { text };\n}\n\nexport default new H3()\n  .get(route, (event) => {\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n    return { workflows };\n  })\n  .all(route + \"/:id\", async (event) => {\n    const id = decodeRouteSegment(event.context.params?.id || \"\");\n\n    // Verify the secret before consulting the workflow id map so the\n    // existing-vs-missing distinction is not disclosed to callers without\n    // the secret (a 401 for unknown ids would otherwise become a 404 oracle).\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n\n    if (!workflowIds.has(id)) {\n      return json({ error: \"Workflow \" + id + \" was not found.\" }, 404);\n    }\n\n    let payload;\n    try {\n      payload = await readPayload(event);\n    } catch (error) {\n      const response = createFarmRequestBodyErrorResponse(error);\n      if (response) return response;\n      if (error instanceof SyntaxError) return json({ error: \"Invalid workflow request body.\" }, 400);\n      throw error;\n    }\n    const result = await runTask(id, {\n      payload,\n      context: {\n        source: \"http\",\n        request: event.req,\n        route,\n        url: event.url.href,\n        method: event.req.method\n      }\n    });\n    return {\n      id,\n      ok: true,\n      result: result ?? null\n    };\n  });\n`.trim();\n}\n\nfunction toWorkflowMetadata(workflow: FarmDiscoveredWorkflow) {\n  return {\n    id: workflow.id,\n    description: workflow.description || null,\n    schedule: workflow.schedule,\n    timezone: workflow.timezone || null,\n    path: workflow.routePath,\n  };\n}\n\nasync function readWorkflowPayload(request: Request, bodySizeLimit: number): Promise<unknown> {\n  const url = new URL(request.url);\n  if (request.method === \"GET\" || request.method === \"HEAD\") {\n    return searchParamsToObject(url.searchParams);\n  }\n\n  const bytes = await readFarmRequestBody(request, bodySizeLimit);\n  const text = new TextDecoder().decode(bytes);\n  if (!text) return {};\n  const contentType = (request.headers.get(\"content-type\") || \"\")\n    .split(\";\", 1)[0]\n    .trim()\n    .toLowerCase();\n  if (\n    contentType === \"application/json\" ||\n    (contentType.startsWith(\"application/\") && contentType.endsWith(\"+json\"))\n  ) {\n    return JSON.parse(text);\n  }\n\n  return { text };\n}\n\nfunction readScheduledTime(payload: unknown): number | string | undefined {\n  return payload && typeof payload === \"object\" && \"scheduledTime\" in payload\n    ? (payload as { scheduledTime?: number | string }).scheduledTime\n    : undefined;\n}\n\nfunction verifyWorkflowSecret(\n  request: Request,\n  config: FarmWorkflowsResolvedConfig,\n): Response | null {\n  const secret = config.secret || readFarmEnvironmentValue(config.secretEnv) || \"\";\n  if (!secret) {\n    // No secret configured. Local development stays convenient, but a deployed\n    // runtime must not expose a route that lists and executes workflows to\n    // anonymous callers. Opt back in explicitly with .\n    if (config.allowUnsecured === true || !isFarmDeployedRuntime()) return null;\n    return Response.json(\n      {\n        error: MISSING_FARM_WORKFLOW_SECRET_ERROR,\n      },\n      { status: 401 },\n    );\n  }\n\n  const authorization = request.headers.get(\"authorization\") || \"\";\n  const bearer = authorization.match(/^Bearer\\s+(.+)$/i)?.[1] || \"\";\n  const headerSecret = request.headers.get(\"x-farm-workflow-secret\") || \"\";\n  if (farmSecretsMatch(bearer, secret) || farmSecretsMatch(headerSecret, secret)) return null;\n\n  return Response.json({ error: \"Unauthorized workflow request.\" }, { status: 401 });\n}\n\nfunction joinRoute(...parts: string[]): string {\n  return `/${parts\n    .map((part) => trimSlashes(part))\n    .filter(Boolean)\n    .join(\"/\")}`;\n}\n\nfunction trimSlashes(value: string): string {\n  return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\n/**\n * Wrapper file names for a set of workflow ids.\n *\n * `safeFileName` is not injective: it maps `a/b` and `a-b` onto the same string,\n * and macOS and Windows additionally fold `Daily` onto `daily` on their default\n * case-insensitive filesystems. Two workflows would then share one generated\n * wrapper and both run whichever was written last. Only ids that actually\n * collide are disambiguated, so ordinary ids keep a readable wrapper; every id\n * in a colliding group gets a digest of the exact id appended, which keeps the\n * result independent of discovery order.\n */\nfunction resolveWorkflowWrapperFileNames(ids: readonly string[]): Map<string, string> {\n  const groups = new Map<string, number>();\n  for (const id of ids) {\n    const key = safeFileName(id).toLowerCase();\n    groups.set(key, (groups.get(key) ?? 0) + 1);\n  }\n\n  const resolved = new Map<string, string>();\n  const claimed = new Map<string, string>();\n  for (const id of ids) {\n    const base = safeFileName(id);\n    const key = base.toLowerCase();\n    const fileName = (groups.get(key) ?? 0) > 1 ? `${key}-${workflowIdFingerprint(id)}` : base;\n    const claimedBy = claimed.get(fileName.toLowerCase());\n    if (claimedBy !== undefined) {\n      throw new Error(\n        `Farm workflows ${JSON.stringify(claimedBy)} and ${JSON.stringify(id)} generate the same wrapper file ${JSON.stringify(`${fileName}.mjs`)}. Rename one of them.`,\n      );\n    }\n    claimed.set(fileName.toLowerCase(), id);\n    resolved.set(id, fileName);\n  }\n  return resolved;\n}\n\n/**\n * FNV-1a. This module is bundled into server runtimes that do not provide\n * node:crypto, and the digest only needs to separate file names.\n */\nfunction workflowIdFingerprint(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < value.length; index += 1) {\n    hash ^= value.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction safeFileName(value: string): string {\n  return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"workflow\";\n}\n\nfunction relativePath(root: string, filePath: string): string {\n  return filePath.replace(/\\\\/g, \"/\").replace(`${root.replace(/\\\\/g, \"/\")}/`, \"\");\n}\n","import { farmSecretsMatch } from \"./secret-compare\";\nimport { toPosixPath } from \"./utils\";\nimport {\n  getFarmRuntimeBindings,\n  readFarmEnvironmentValue as readEnvironmentValue,\n} from \"./utils/runtime-env\";\n\nexport type FarmCronSchedule = string | string[];\n\nexport interface FarmCronJobConfig {\n  /** Portable five-field cron expression, or a list of expressions. */\n  schedule: FarmCronSchedule;\n  /** Farm API route invoked with GET when the schedule fires. */\n  path: string;\n  /** Human-readable purpose shown by local tooling and deployment manifests. */\n  description?: string;\n  /** Disable this schedule without removing its configuration. */\n  enabled?: boolean;\n}\n\nexport type FarmCronUserConfig = Record<string, FarmCronJobConfig>;\n\nexport interface FarmCronJob {\n  name: string;\n  schedule: string[];\n  path: string;\n  description?: string;\n}\n\nexport interface FarmCronResolvedConfig {\n  enabled: boolean;\n  secretEnv: typeof DEFAULT_FARM_CRON_SECRET_ENV;\n  jobs: FarmCronJob[];\n}\n\nexport interface PreparedFarmCron {\n  jobs: FarmCronJob[];\n  tasks: Record<string, { handler: string; description: string }>;\n  scheduledTasks: Record<string, string | string[]>;\n  manifestPath?: string;\n}\n\nexport interface FarmCronRouteOptions {\n  /** Environment variable containing the bearer token. */\n  secretEnv?: string;\n  /** Inline token, primarily useful in tests. Environment variables are preferred. */\n  secret?: string;\n  /** Allow a production route without a secret. Defaults to false. */\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmCronCloudflareConfig {\n  deployConfig: true;\n  wrangler: {\n    triggers: {\n      crons: string[];\n    };\n  };\n}\n\nexport const DEFAULT_FARM_CRON_SECRET_ENV = \"CRON_SECRET\";\nexport const FARM_CRON_MANIFEST = \"cron-manifest.json\";\n\nconst CRON_FIELD_RANGES = [\n  [0, 59, \"minute\"],\n  [0, 23, \"hour\"],\n  [1, 31, \"day of month\"],\n  [1, 12, \"month\"],\n  [0, 6, \"day of week\"],\n] as const;\n\nexport function resolveCronConfig(\n  cron: FarmCronResolvedConfig | FarmCronUserConfig | false | undefined,\n): FarmCronResolvedConfig {\n  if (isResolvedCronConfig(cron)) return cron;\n  if (!cron) {\n    return {\n      enabled: false,\n      secretEnv: DEFAULT_FARM_CRON_SECRET_ENV,\n      jobs: [],\n    };\n  }\n\n  const jobs: FarmCronJob[] = [];\n  for (const [name, job] of Object.entries(cron)) {\n    if (!job || typeof job !== \"object\" || Array.isArray(job)) {\n      throw new TypeError(`Farm cron ${JSON.stringify(name)} must be a configuration object.`);\n    }\n    if (job.enabled === false) continue;\n    jobs.push(normalizeCronJob(name, job));\n  }\n\n  return {\n    enabled: jobs.length > 0,\n    secretEnv: DEFAULT_FARM_CRON_SECRET_ENV,\n    jobs,\n  };\n}\n\nexport async function prepareFarmCronForNitro(config: {\n  root?: string;\n  distDir?: string;\n  cron?: FarmCronResolvedConfig | FarmCronUserConfig | false;\n}): Promise<PreparedFarmCron> {\n  const cron = isResolvedCronConfig(config.cron) ? config.cron : resolveCronConfig(config.cron);\n  const root = config.root || process.cwd();\n  const distDir = config.distDir || \".farm\";\n  const fs = await import(\"node:fs/promises\");\n  const path = await import(\"node:path\");\n  const manifestPath = path.join(root, distDir, FARM_CRON_MANIFEST);\n  const generatedDir = path.join(root, distDir, \".nitro\", \"farm-cron\");\n\n  if (!cron.enabled) {\n    await Promise.all([\n      fs.rm(manifestPath, { force: true }),\n      fs.rm(generatedDir, { recursive: true, force: true }),\n    ]);\n    return {\n      jobs: [],\n      tasks: {},\n      scheduledTasks: {},\n    };\n  }\n\n  await fs.rm(generatedDir, { recursive: true, force: true });\n  await fs.mkdir(generatedDir, { recursive: true });\n\n  const tasks: PreparedFarmCron[\"tasks\"] = {};\n  const wrapperNames = resolveCronWrapperFileNames(cron.jobs.map((job) => job.name));\n  for (const job of cron.jobs) {\n    const taskName = getFarmCronTaskName(job.name);\n    const wrapperPath = toPosixPath(path.join(generatedDir, `${wrapperNames.get(job.name)}.mjs`));\n    await fs.writeFile(wrapperPath, createNitroCronTaskWrapper(job, cron.secretEnv), \"utf8\");\n    tasks[taskName] = {\n      handler: wrapperPath,\n      description: job.description || `Farm cron ${job.name}`,\n    };\n  }\n\n  const manifest = createFarmCronManifest(cron);\n  await fs.mkdir(path.dirname(manifestPath), { recursive: true });\n  await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\");\n\n  return {\n    jobs: cron.jobs,\n    tasks,\n    scheduledTasks: createCronScheduledTasks(cron.jobs),\n    manifestPath,\n  };\n}\n\nexport function createFarmCronManifest(cron: FarmCronResolvedConfig) {\n  return {\n    schemaVersion: 1,\n    secretEnv: cron.secretEnv,\n    jobs: cron.jobs.map((job) => ({\n      name: job.name,\n      schedule: job.schedule,\n      path: job.path,\n      description: job.description || null,\n    })),\n  };\n}\n\nexport function createFarmCronVercelCrons(\n  jobs: FarmCronJob[],\n): Array<{ path: string; schedule: string }> {\n  return jobs.flatMap((job) =>\n    job.schedule.map((schedule) => ({\n      path: job.path,\n      schedule,\n    })),\n  );\n}\n\nexport function applyFarmCronVercelCrons(\n  vercelConfig: Record<string, any>,\n  jobs: FarmCronJob[],\n): Record<string, any> {\n  const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n  const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n  const crons = [...existingCrons];\n\n  for (const cron of createFarmCronVercelCrons(jobs)) {\n    const key = `${cron.path}:${cron.schedule}`;\n    if (seen.has(key)) continue;\n    seen.add(key);\n    crons.push(cron);\n  }\n\n  return crons.length > 0 ? { ...vercelConfig, crons } : vercelConfig;\n}\n\nexport function createFarmCronCloudflareTriggers(jobs: FarmCronJob[]): string[] {\n  return [...new Set(jobs.flatMap((job) => job.schedule))];\n}\n\nexport function createFarmCronCloudflareConfig(\n  jobs: FarmCronJob[],\n): FarmCronCloudflareConfig | undefined {\n  const crons = createFarmCronCloudflareTriggers(jobs);\n  if (crons.length === 0) return undefined;\n\n  return {\n    deployConfig: true,\n    wrangler: {\n      triggers: { crons },\n    },\n  };\n}\n\nexport function mergeScheduledTasks(\n  ...maps: Array<Record<string, string | string[]> | undefined>\n): Record<string, string | string[]> {\n  const merged = new Map<string, string[]>();\n\n  for (const map of maps) {\n    for (const [schedule, taskNames] of Object.entries(map || {})) {\n      const current = merged.get(schedule) || [];\n      for (const taskName of Array.isArray(taskNames) ? taskNames : [taskNames]) {\n        if (!current.includes(taskName)) current.push(taskName);\n      }\n      merged.set(schedule, current);\n    }\n  }\n\n  return Object.fromEntries(\n    [...merged].map(([schedule, taskNames]) => [\n      schedule,\n      taskNames.length === 1 ? taskNames[0] : taskNames,\n    ]),\n  );\n}\n\n/**\n * Whether the process explicitly declares a development or test environment.\n *\n * An absent NODE_ENV is not a development signal. Plenty of container images and\n * serverless runtimes leave it unset, so treating \"not production\" as\n * development leaves an unsecured cron route open wherever the variable simply\n * was never set. Matches the fail-closed gate the auth0 and workos integrations\n * use for their development secrets.\n */\nfunction isExplicitDevelopmentEnv(): boolean {\n  const nodeEnv = readEnvironmentValue(\"NODE_ENV\");\n  return nodeEnv === \"development\" || nodeEnv === \"test\";\n}\n\nexport function isCronRequestAuthorized(\n  request: Request,\n  options: FarmCronRouteOptions = {},\n): boolean {\n  const secretEnv = options.secretEnv || DEFAULT_FARM_CRON_SECRET_ENV;\n  const secret = options.secret || readEnvironmentValue(secretEnv);\n  if (!secret) {\n    return (\n      options.allowUnsecured === true || (!getFarmRuntimeBindings() && isExplicitDevelopmentEnv())\n    );\n  }\n\n  const authorization = request.headers.get(\"authorization\") || \"\";\n  const bearer = /^Bearer (.*)$/i.exec(authorization)?.[1] || \"\";\n  const headerSecret = request.headers.get(\"x-farm-cron-secret\") || \"\";\n  // Both are checked so a caller may use either header; neither short-circuits\n  // on the first differing character.\n  return farmSecretsMatch(bearer, secret) || farmSecretsMatch(headerSecret, secret);\n}\n\nexport function cronRoute<TArgs extends unknown[], TResult>(\n  handler: (request: Request, ...args: TArgs) => TResult,\n  options: FarmCronRouteOptions = {},\n): (request: Request, ...args: TArgs) => TResult | Promise<Response> {\n  return (request, ...args) => {\n    if (!isCronRequestAuthorized(request, options)) {\n      return Promise.resolve(\n        Response.json({ error: \"Unauthorized cron request.\" }, { status: 401 }),\n      );\n    }\n    return handler(request, ...args);\n  };\n}\n\nfunction normalizeCronJob(name: string, job: FarmCronJobConfig): FarmCronJob {\n  if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)) {\n    throw new TypeError(\n      `Farm cron name ${JSON.stringify(name)} must start with a letter or number and contain only letters, numbers, dots, underscores, or hyphens.`,\n    );\n  }\n  if (!job || typeof job !== \"object\" || Array.isArray(job)) {\n    throw new TypeError(`Farm cron ${JSON.stringify(name)} must be a configuration object.`);\n  }\n\n  const path = normalizeCronPath(name, job.path);\n  const rawSchedule = Array.isArray(job.schedule) ? job.schedule : [job.schedule];\n  const schedule = [...new Set(rawSchedule.map((value) => normalizeCronExpression(name, value)))];\n  if (schedule.length === 0) {\n    throw new TypeError(`Farm cron ${JSON.stringify(name)} must define at least one schedule.`);\n  }\n\n  return {\n    name,\n    schedule,\n    path,\n    description: job.description?.trim() || undefined,\n  };\n}\n\nfunction normalizeCronPath(name: string, value: unknown): string {\n  if (typeof value !== \"string\" || !value.trim().startsWith(\"/\")) {\n    throw new TypeError(`Farm cron ${JSON.stringify(name)} path must start with \"/\".`);\n  }\n\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n  if (hasUnstableCharacters(value)) {\n    throw new TypeError(\n      `Farm cron ${JSON.stringify(name)} path cannot contain backslashes or control characters.`,\n    );\n  }\n\n  const path = value.trim();\n  if (path.startsWith(\"//\") || path.includes(\"?\") || path.includes(\"#\")) {\n    throw new TypeError(\n      `Farm cron ${JSON.stringify(name)} path must be an application pathname without a host, query, or hash.`,\n    );\n  }\n  for (const segment of path.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal and cannot conceal a separator or dot segment.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new TypeError(\n        `Farm cron ${JSON.stringify(name)} path cannot contain backslashes or control characters.`,\n      );\n    }\n    if (decoded.includes(\"/\")) {\n      throw new TypeError(\n        `Farm cron ${JSON.stringify(name)} path cannot contain percent-encoded path separators.`,\n      );\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new TypeError(\n        `Farm cron ${JSON.stringify(name)} path cannot contain \".\" or \"..\" path segments.`,\n      );\n    }\n  }\n  return path.length > 1 ? path.replace(/\\/+$/, \"\") : path;\n}\n\nfunction normalizeCronExpression(name: string, value: unknown): string {\n  if (typeof value !== \"string\") {\n    throw new TypeError(`Farm cron ${JSON.stringify(name)} schedule must be a string.`);\n  }\n\n  const expression = value.trim().replace(/\\s+/g, \" \");\n  const fields = expression.split(\" \");\n  if (fields.length !== CRON_FIELD_RANGES.length) {\n    throw new TypeError(\n      `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} must use five fields: minute hour day-of-month month day-of-week.`,\n    );\n  }\n\n  fields.forEach((field, index) => {\n    const [minimum, maximum, label] = CRON_FIELD_RANGES[index];\n    validateCronField(name, expression, field, minimum, maximum, label);\n  });\n  if (fields[2] !== \"*\" && fields[4] !== \"*\") {\n    throw new TypeError(\n      `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} cannot constrain both day-of-month and day-of-week.`,\n    );\n  }\n  return expression;\n}\n\nfunction validateCronField(\n  name: string,\n  expression: string,\n  field: string,\n  minimum: number,\n  maximum: number,\n  label: string,\n): void {\n  for (const segment of field.split(\",\")) {\n    const [range, stepText, ...extra] = segment.split(\"/\");\n    if (!range || extra.length > 0 || (stepText !== undefined && !isIntegerInRange(stepText, 1))) {\n      throwInvalidCronField(name, expression, label);\n    }\n\n    if (range === \"*\") continue;\n    const bounds = range.split(\"-\");\n    if (bounds.length > 2 || !bounds.every((value) => isIntegerInRange(value, minimum, maximum))) {\n      throwInvalidCronField(name, expression, label);\n    }\n    if (bounds.length === 2 && Number(bounds[0]) > Number(bounds[1])) {\n      throwInvalidCronField(name, expression, label);\n    }\n  }\n}\n\nfunction isIntegerInRange(value: string, minimum: number, maximum = Number.MAX_SAFE_INTEGER) {\n  if (!/^\\d+$/.test(value)) return false;\n  const parsed = Number(value);\n  return parsed >= minimum && parsed <= maximum;\n}\n\nfunction throwInvalidCronField(name: string, expression: string, label: string): never {\n  throw new TypeError(\n    `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} has an invalid ${label} field.`,\n  );\n}\n\nfunction isResolvedCronConfig(value: unknown): value is FarmCronResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"enabled\" in value &&\n    typeof (value as FarmCronResolvedConfig).enabled === \"boolean\" &&\n    \"jobs\" in value &&\n    Array.isArray((value as FarmCronResolvedConfig).jobs) &&\n    \"secretEnv\" in value\n  );\n}\n\nfunction createCronScheduledTasks(jobs: FarmCronJob[]): Record<string, string | string[]> {\n  const scheduledTasks: Record<string, string | string[]> = {};\n  for (const job of jobs) {\n    const taskName = getFarmCronTaskName(job.name);\n    for (const schedule of job.schedule) {\n      scheduledTasks[schedule] = mergeTaskNames(scheduledTasks[schedule], taskName);\n    }\n  }\n  return scheduledTasks;\n}\n\nfunction mergeTaskNames(\n  current: string | string[] | undefined,\n  taskName: string,\n): string | string[] {\n  if (!current) return taskName;\n  const names = Array.isArray(current) ? current : [current];\n  return names.includes(taskName) ? names : [...names, taskName];\n}\n\nfunction getFarmCronTaskName(name: string): string {\n  return `farm:cron:${name}`;\n}\n\nfunction createNitroCronTaskWrapper(job: FarmCronJob, secretEnv: string): string {\n  return `\nimport { defineTask, useNitroApp } from \"nitro/runtime\";\n\nconst name = ${JSON.stringify(job.name)};\nconst path = ${JSON.stringify(job.path)};\nconst secretEnv = ${JSON.stringify(secretEnv)};\n\nfunction readSecret(event) {\n  const runtimeEnv = event?.context?.cloudflare?.env || event?.context?.env || {};\n  return runtimeEnv[secretEnv] || (typeof process !== \"undefined\" ? process.env?.[secretEnv] : \"\") || \"\";\n}\n\nexport default defineTask({\n  meta: {\n    name: ${JSON.stringify(getFarmCronTaskName(job.name))},\n    description: ${JSON.stringify(job.description || `Farm cron ${job.name}`)}\n  },\n  async run(event) {\n    const headers = new Headers({\n      \"x-farm-cron-name\": name,\n      \"x-farm-cron-scheduled-at\": String(event?.payload?.scheduledTime || Date.now())\n    });\n    const secret = readSecret(event);\n    if (secret) headers.set(\"authorization\", \"Bearer \" + secret);\n\n    const response = await useNitroApp().fetch(path, { method: \"GET\", headers });\n    const contentType = response.headers.get(\"content-type\") || \"\";\n    const body = response.status === 204\n      ? null\n      : contentType.includes(\"application/json\")\n        ? await response.json().catch(() => null)\n        : await response.text();\n\n    if (!response.ok) {\n      const detail = typeof body === \"string\" ? body : JSON.stringify(body);\n      throw new Error(\n        \"Farm cron \" + JSON.stringify(name) + \" received \" + response.status +\n        \" from \" + path + (detail ? \": \" + detail : \"\")\n      );\n    }\n\n    return { result: body };\n  }\n});\n`.trim();\n}\n\n/**\n * Wrapper file names for a set of cron job names.\n *\n * Cron names are case-sensitive and `Daily` and `daily` are both valid, distinct\n * jobs — but macOS and Windows use case-insensitive filesystems by default, so\n * their wrappers would overwrite one another and both jobs would run whichever\n * file was written last. Names are only disambiguated when they actually\n * collide case-insensitively, so ordinary names such as `dailyCleanup` keep a\n * readable wrapper; every name in a colliding group gets a digest of the exact\n * job name appended, which keeps the result independent of configuration order.\n */\nfunction resolveCronWrapperFileNames(names: readonly string[]): Map<string, string> {\n  const groups = new Map<string, number>();\n  for (const name of names) {\n    const key = safeFileName(name).toLowerCase();\n    groups.set(key, (groups.get(key) ?? 0) + 1);\n  }\n\n  const resolved = new Map<string, string>();\n  const claimed = new Map<string, string>();\n  for (const name of names) {\n    const base = safeFileName(name);\n    const key = base.toLowerCase();\n    const fileName = (groups.get(key) ?? 0) > 1 ? `${key}-${cronNameFingerprint(name)}` : base;\n    const claimedBy = claimed.get(fileName.toLowerCase());\n    if (claimedBy !== undefined) {\n      throw new Error(\n        `Farm cron jobs ${JSON.stringify(claimedBy)} and ${JSON.stringify(name)} generate the same wrapper file ${JSON.stringify(`${fileName}.mjs`)}. Rename one of them.`,\n      );\n    }\n    claimed.set(fileName.toLowerCase(), name);\n    resolved.set(name, fileName);\n  }\n  return resolved;\n}\n\n/**\n * FNV-1a. This module is bundled into server runtimes without node:crypto, and\n * the digest only needs to separate file names.\n */\nfunction cronNameFingerprint(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < value.length; index += 1) {\n    hash ^= value.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction safeFileName(value: string): string {\n  return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"cron\";\n}\n","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 type React from \"react\";\n\nexport type FarmMdxComponent = React.ComponentType<any> | keyof React.JSX.IntrinsicElements;\nexport type FarmMdxComponents = Record<string, FarmMdxComponent>;\n\nexport interface FarmMdxUserConfig {\n  /**\n   * Component map or module path that exports `components` or a default component map.\n   * Relative paths resolve from the project root.\n   */\n  components?: string | FarmMdxComponents;\n  /**\n   * Serve source-authored markdown pages at `/route.md`.\n   * Enabled by default for `page.md` and `page.mdx`.\n   */\n  markdownRoutes?: boolean;\n  /** Class name used for the wrapper around rendered markdown content. */\n  className?: string;\n}\n\nexport interface FarmMdxResolvedConfig {\n  components?: string | FarmMdxComponents;\n  markdownRoutes: boolean;\n  className: string;\n}\n\nexport function resolveMdxConfig(config: FarmMdxUserConfig | undefined): FarmMdxResolvedConfig {\n  return {\n    components: config?.components,\n    markdownRoutes: config?.markdownRoutes ?? true,\n    className: config?.className ?? \"farm-markdown\",\n  };\n}\n","export type FarmRedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nexport interface FarmRedirectSignal {\n  url: string;\n  status: FarmRedirectStatus;\n}\n\nconst REDIRECT_ERROR_CODE = \"FARM_REDIRECT\";\nconst NOT_FOUND_ERROR_CODE = \"FARM_NOT_FOUND\";\nconst REDIRECT_ERROR_SYMBOL = Symbol.for(\"farm.navigation.redirect\");\nconst NOT_FOUND_ERROR_SYMBOL = Symbol.for(\"farm.navigation.notFound\");\n\ntype FarmNavigationError = Error & {\n  digest: string;\n  [REDIRECT_ERROR_SYMBOL]?: FarmRedirectSignal;\n  [NOT_FOUND_ERROR_SYMBOL]?: true;\n};\n\nexport function redirect(url: string, status: FarmRedirectStatus = 307): never {\n  throw createRedirectError(url, status);\n}\n\nexport function permanentRedirect(url: string): never {\n  redirect(url, 308);\n}\n\nexport function notFound(): never {\n  const error = new Error(NOT_FOUND_ERROR_CODE) as FarmNavigationError;\n  error.digest = NOT_FOUND_ERROR_CODE;\n  error[NOT_FOUND_ERROR_SYMBOL] = true;\n  throw error;\n}\n\nexport function isFarmRedirectError(error: unknown): boolean {\n  return Boolean(getFarmRedirectError(error));\n}\n\nexport function getFarmRedirectError(error: unknown): FarmRedirectSignal | null {\n  if (!error || typeof error !== \"object\") return null;\n  const candidate = error as Partial<FarmNavigationError>;\n  if (candidate[REDIRECT_ERROR_SYMBOL]) {\n    return candidate[REDIRECT_ERROR_SYMBOL] as FarmRedirectSignal;\n  }\n\n  if (\n    typeof candidate.digest === \"string\" &&\n    candidate.digest.startsWith(`${REDIRECT_ERROR_CODE};`)\n  ) {\n    const [, status, ...urlParts] = candidate.digest.split(\";\");\n    const parsedStatus = Number(status);\n    if (isFarmRedirectStatus(parsedStatus)) {\n      return {\n        status: parsedStatus,\n        url: urlParts.join(\";\"),\n      };\n    }\n  }\n\n  return null;\n}\n\nexport function isFarmNotFoundError(error: unknown): boolean {\n  if (!error || typeof error !== \"object\") return false;\n  const candidate = error as Partial<FarmNavigationError>;\n  return Boolean(candidate[NOT_FOUND_ERROR_SYMBOL] || candidate.digest === NOT_FOUND_ERROR_CODE);\n}\n\nfunction createRedirectError(url: string, status: FarmRedirectStatus): FarmNavigationError {\n  const error = new Error(`${REDIRECT_ERROR_CODE};${status};${url}`) as FarmNavigationError;\n  error.digest = `${REDIRECT_ERROR_CODE};${status};${url}`;\n  error[REDIRECT_ERROR_SYMBOL] = { url, status };\n  return error;\n}\n\nexport function isFarmRedirectStatus(status: unknown): status is FarmRedirectStatus {\n  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;\n}\n","export type FarmRouteRuntime = \"auto\" | \"node\" | \"edge\";\nexport type FarmRouteRegions = \"auto\" | readonly string[];\nexport type FarmRouteMaxDuration = \"auto\" | number;\n\n/** Portable execution controls shared by file, programmatic, and config routes. */\nexport interface FarmRouteRuntimeConfig {\n  runtime?: FarmRouteRuntime;\n  regions?: FarmRouteRegions;\n  maxDuration?: FarmRouteMaxDuration;\n}\n\nexport interface ResolvedFarmRouteRuntimeConfig {\n  runtime: FarmRouteRuntime;\n  regions?: string[];\n  maxDuration?: number;\n}\n\nexport type FarmRouteRuntimeEntryKind = \"page\" | \"api\" | \"metadata\" | \"rule\";\nexport type FarmRouteRenderingMode = \"static\" | \"dynamic\";\n\nexport interface FarmRouteRuntimeManifestEntry extends ResolvedFarmRouteRuntimeConfig {\n  kind: FarmRouteRuntimeEntryKind;\n  pattern: string;\n  rendering: FarmRouteRenderingMode;\n  source?: string;\n}\n\nexport interface FarmRouteRuntimeManifest {\n  version: 1;\n  routes: FarmRouteRuntimeManifestEntry[];\n}\n\nexport function normalizeFarmRouteRuntimeConfig(\n  value: FarmRouteRuntimeConfig | null | undefined,\n  source = \"Route configuration\",\n): FarmRouteRuntimeConfig {\n  if (!value) return {};\n\n  const normalized: FarmRouteRuntimeConfig = {};\n\n  if (value.runtime !== undefined) {\n    if (value.runtime !== \"auto\" && value.runtime !== \"node\" && value.runtime !== \"edge\") {\n      throw new TypeError(`${source} runtime must be \"auto\", \"node\", or \"edge\"`);\n    }\n    normalized.runtime = value.runtime;\n  }\n\n  if (value.regions !== undefined) {\n    if (value.regions === \"auto\") {\n      normalized.regions = \"auto\";\n    } else {\n      if (!Array.isArray(value.regions) || value.regions.length === 0) {\n        throw new TypeError(`${source} regions must be \"auto\" or a non-empty string array`);\n      }\n\n      const regions = Array.from(\n        new Set(\n          value.regions.map((region) => {\n            if (\n              typeof region !== \"string\" ||\n              !region.trim() ||\n              /[\\u0000-\\u001f\\u007f]/.test(region)\n            ) {\n              throw new TypeError(`${source} regions must contain non-empty region identifiers`);\n            }\n            return region.trim();\n          }),\n        ),\n      );\n\n      normalized.regions = regions;\n    }\n  }\n\n  if (value.maxDuration !== undefined) {\n    if (value.maxDuration === \"auto\") {\n      normalized.maxDuration = \"auto\";\n    } else if (\n      typeof value.maxDuration !== \"number\" ||\n      !Number.isInteger(value.maxDuration) ||\n      value.maxDuration <= 0\n    ) {\n      throw new TypeError(`${source} maxDuration must be \"auto\" or a positive integer in seconds`);\n    } else {\n      normalized.maxDuration = value.maxDuration;\n    }\n  }\n\n  return normalized;\n}\n\n/** Merge from lowest to highest precedence. Explicit \"auto\" values reset inherited hints. */\nexport function mergeFarmRouteRuntimeConfigs(\n  ...configs: Array<FarmRouteRuntimeConfig | null | undefined>\n): FarmRouteRuntimeConfig {\n  const merged: FarmRouteRuntimeConfig = {};\n\n  for (const config of configs) {\n    if (!config) continue;\n    if (config.runtime !== undefined) merged.runtime = config.runtime;\n    if (config.regions !== undefined) merged.regions = config.regions;\n    if (config.maxDuration !== undefined) merged.maxDuration = config.maxDuration;\n  }\n\n  return merged;\n}\n\nexport function resolveFarmRouteRuntimeConfig(\n  config: FarmRouteRuntimeConfig | null | undefined,\n  source?: string,\n): ResolvedFarmRouteRuntimeConfig {\n  const normalized = normalizeFarmRouteRuntimeConfig(config, source);\n\n  return {\n    runtime: normalized.runtime ?? \"auto\",\n    ...(normalized.regions && normalized.regions !== \"auto\"\n      ? { regions: [...normalized.regions] }\n      : {}),\n    ...(typeof normalized.maxDuration === \"number\" ? { maxDuration: normalized.maxDuration } : {}),\n  };\n}\n\nexport function hasFarmRouteRuntimeControls(\n  config: FarmRouteRuntimeConfig | null | undefined,\n): boolean {\n  return Boolean(\n    config &&\n    (config.runtime !== undefined ||\n      config.regions !== undefined ||\n      config.maxDuration !== undefined),\n  );\n}\n\nexport function getFarmRouteRuntimeConfig(value: unknown): FarmRouteRuntimeConfig {\n  if (!value || typeof value !== \"object\") return {};\n  const route = value as FarmRouteRuntimeConfig;\n  return {\n    ...(route.runtime !== undefined ? { runtime: route.runtime } : {}),\n    ...(route.regions !== undefined ? { regions: route.regions } : {}),\n    ...(route.maxDuration !== undefined ? { maxDuration: route.maxDuration } : {}),\n  };\n}\n\nexport function createFarmRouteRuntimeKey(config: ResolvedFarmRouteRuntimeConfig): string {\n  return JSON.stringify({\n    runtime: config.runtime,\n    regions: config.regions || null,\n    maxDuration: config.maxDuration || null,\n  });\n}\n\n/** Resolve matching route rules from broadest to most specific. */\nexport function resolveFarmRouteRuleRuntimeConfig(\n  pathname: string,\n  routeRules: Record<string, FarmRouteRuntimeConfig> | null | undefined,\n): FarmRouteRuntimeConfig {\n  if (!routeRules) return {};\n\n  const matches = Object.entries(routeRules)\n    .filter(\n      ([pattern, rule]) =>\n        hasFarmRouteRuntimeControls(rule) && farmRouteRuleMatches(pattern, pathname),\n    )\n    .sort(([left], [right]) => compareFarmRouteRuleSpecificity(left, right));\n\n  return mergeFarmRouteRuntimeConfigs(...matches.map(([, rule]) => rule));\n}\n\nexport function farmRouteRuleMatches(pattern: string, pathname: string): boolean {\n  const normalizedPattern = normalizeRoutePattern(pattern);\n  const normalizedPathname = normalizeRoutePattern(pathname);\n  if (normalizedPattern === normalizedPathname) return true;\n\n  const expression = normalizedPattern\n    .split(\"/\")\n    .filter(Boolean)\n    .map((segment) => {\n      if (segment === \"**\") return \".*\";\n      if (segment === \"*\") return \"[^/]+\";\n      if (/^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)) return \".*\";\n      if (/^\\[\\.\\.\\..+\\]$/.test(segment)) return \".+\";\n      if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return \"[^/]+\";\n      return escapeRegExp(segment);\n    })\n    .join(\"/\");\n\n  return new RegExp(`^/${expression}/?$`).test(normalizedPathname);\n}\n\nfunction compareFarmRouteRuleSpecificity(left: string, right: string): number {\n  const leftScore = getFarmRouteRuleSpecificity(left);\n  const rightScore = getFarmRouteRuleSpecificity(right);\n  return leftScore - rightScore || left.localeCompare(right);\n}\n\nfunction getFarmRouteRuleSpecificity(pattern: string): number {\n  return normalizeRoutePattern(pattern)\n    .split(\"/\")\n    .filter(Boolean)\n    .reduce((score, segment) => {\n      if (segment === \"**\" || segment.startsWith(\"[[...\")) return score + 1;\n      if (segment === \"*\" || segment.startsWith(\"[...\")) return score + 10;\n      if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return score + 50;\n      return score + 100;\n    }, 0);\n}\n\nfunction normalizeRoutePattern(value: string): string {\n  const withSlash = value.trim().startsWith(\"/\") ? value.trim() : `/${value.trim()}`;\n  return withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import type { HeaderConfig, RedirectConfig } from \"./config\";\nimport { isFarmRedirectStatus, type FarmRedirectStatus } from \"./navigation-errors\";\nimport type { FarmRouteRuntimeConfig } from \"./route-runtime\";\nimport { normalizeFarmRouteRuntimeConfig } from \"./route-runtime\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\n\nexport type FarmRouteRuleRenderMode = \"static\" | \"dynamic\";\n\nexport type FarmRouteRuleRedirect =\n  | string\n  | {\n      to: string;\n      statusCode?: FarmRedirectStatus;\n      permanent?: boolean;\n    };\n\nexport type FarmRouteRuleCors =\n  | boolean\n  | {\n      origin?: string;\n      methods?: string | readonly string[];\n      headers?: string | readonly string[];\n    };\n\nexport interface FarmRouteRule extends FarmRouteRuntimeConfig {\n  prerender?: boolean;\n  render?: FarmRouteRuleRenderMode;\n  ssr?: boolean;\n  swr?: boolean | number;\n  isr?: boolean | number;\n  cors?: FarmRouteRuleCors;\n  headers?: Record<string, string>;\n  redirect?: FarmRouteRuleRedirect;\n}\n\nexport type FarmRouteRules = Record<string, FarmRouteRule>;\n\nexport function normalizeRouteRules(routeRules: FarmRouteRules | undefined): FarmRouteRules {\n  if (!routeRules) return {};\n\n  const normalized: FarmRouteRules = {};\n  const normalizedSources = new Map<string, string>();\n  for (const [source, rule] of Object.entries(routeRules)) {\n    if (!rule) continue;\n    const normalizedSource = normalizeRuleSource(source);\n    validateConfigRouteSource(normalizedSource, `Route rule \"${source}\" source`);\n    const existingSource = normalizedSources.get(normalizedSource);\n    if (existingSource !== undefined) {\n      throw new Error(\n        `Route rules \"${existingSource}\" and \"${source}\" both normalize to \"${normalizedSource}\".`,\n      );\n    }\n    normalizedSources.set(normalizedSource, source);\n    if (\n      typeof rule.redirect === \"object\" &&\n      rule.redirect.statusCode !== undefined &&\n      !isFarmRedirectStatus(rule.redirect.statusCode)\n    ) {\n      throw new RangeError(\n        `Route rule \"${normalizedSource}\" redirect.statusCode must be one of 301, 302, 303, 307, or 308.`,\n      );\n    }\n    normalized[normalizedSource] = {\n      ...rule,\n      ...normalizeFarmRouteRuntimeConfig(rule, `Route rule \"${normalizedSource}\"`),\n    };\n  }\n  return normalized;\n}\n\nexport function routeRulesToRedirects(routeRules: FarmRouteRules): RedirectConfig[] {\n  return Object.entries(routeRules)\n    .filter((entry): entry is [string, FarmRouteRule & { redirect: FarmRouteRuleRedirect }] =>\n      Boolean(entry[1].redirect),\n    )\n    .map(([source, rule]) => {\n      const redirect = typeof rule.redirect === \"string\" ? { to: rule.redirect } : rule.redirect;\n      return {\n        source,\n        destination: redirect.to,\n        permanent: redirect.permanent,\n        statusCode: redirect.statusCode ?? (redirect.permanent === true ? 308 : undefined),\n      };\n    });\n}\n\nexport function routeRulesToHeaders(routeRules: FarmRouteRules): HeaderConfig[] {\n  const configs: HeaderConfig[] = [];\n\n  for (const [source, rule] of Object.entries(routeRules)) {\n    const headers = {\n      ...normalizeCorsHeaders(rule.cors),\n      ...rule.headers,\n    };\n\n    const entries = Object.entries(headers);\n    if (entries.length === 0) continue;\n\n    configs.push({\n      source,\n      headers: entries.map(([key, value]) => ({ key, value })),\n    });\n  }\n\n  return configs;\n}\n\nexport function routeRulesToNitroRouteRules(routeRules: FarmRouteRules): Record<string, any> {\n  const nitroRules: Record<string, any> = {};\n\n  for (const [source, rule] of Object.entries(routeRules)) {\n    const nitroRule: Record<string, any> = { ...rule };\n\n    if (rule.render === \"static\") {\n      nitroRule.prerender = true;\n    } else if (rule.render === \"dynamic\") {\n      nitroRule.prerender = false;\n    }\n\n    if (rule.redirect) {\n      const redirect = typeof rule.redirect === \"string\" ? { to: rule.redirect } : rule.redirect;\n      if (hasExplicitQuery(redirect.to)) {\n        // Nitro merges the incoming query into redirect targets, including when\n        // the target already declares one. Farm's redirect contract replaces\n        // the incoming query in that case, so let the bundled Farm handler own\n        // these redirects instead of changing their meaning in production.\n        delete nitroRule.redirect;\n      } else {\n        nitroRule.redirect = {\n          to: redirect.to,\n          status: redirect.statusCode ?? (redirect.permanent === true ? 308 : 307),\n        };\n      }\n    }\n\n    if (rule.cors) {\n      nitroRule.cors = true;\n      nitroRule.headers = {\n        ...normalizeCorsHeaders(rule.cors),\n        ...rule.headers,\n      };\n    }\n\n    delete nitroRule.render;\n    delete nitroRule.runtime;\n    delete nitroRule.regions;\n    delete nitroRule.maxDuration;\n    nitroRules[source] = nitroRule;\n  }\n\n  return nitroRules;\n}\n\nfunction normalizeCorsHeaders(cors: FarmRouteRuleCors | undefined): Record<string, string> {\n  if (!cors) return {};\n\n  if (cors === true) {\n    return {\n      \"Access-Control-Allow-Origin\": \"*\",\n      \"Access-Control-Allow-Methods\": \"*\",\n      \"Access-Control-Allow-Headers\": \"*\",\n    };\n  }\n\n  return {\n    \"Access-Control-Allow-Origin\": cors.origin ?? \"*\",\n    \"Access-Control-Allow-Methods\": normalizeList(cors.methods) ?? \"*\",\n    \"Access-Control-Allow-Headers\": normalizeList(cors.headers) ?? \"*\",\n  };\n}\n\nfunction normalizeList(value: string | readonly string[] | undefined): string | undefined {\n  if (!value || typeof value === \"string\") return value;\n  return value.join(\", \");\n}\n\nfunction normalizeRuleSource(source: string): string {\n  const trimmed = source.trim();\n  if (!trimmed) {\n    throw new TypeError(\"Route rule source must be a non-empty pathname pattern.\");\n  }\n  return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\nfunction hasExplicitQuery(destination: string): boolean {\n  const queryIndex = destination.indexOf(\"?\");\n  if (queryIndex === -1) return false;\n  const hashIndex = destination.indexOf(\"#\");\n  return hashIndex === -1 || queryIndex < hashIndex;\n}\n","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","export const FARM_DEPLOYMENT_ID_HEADER = \"x-farm-deployment-id\";\nexport const FARM_DEPLOYMENT_MISMATCH_HEADER = \"x-farm-deployment-mismatch\";\nexport const FARM_DEPLOYMENT_COOKIE = \"__farm_deployment\";\nexport const FARM_DEPLOYMENT_MISMATCH_CODE = \"FARM_DEPLOYMENT_MISMATCH\";\nexport const FARM_DEPLOYMENT_MISMATCH_STATUS = 409;\n\nexport type FarmPresetRuntime = \"node\" | \"edge\" | \"unknown\";\n\nexport function getFarmPresetRuntime(preset: string): FarmPresetRuntime {\n  if (\n    preset === \"cloudflare\" ||\n    preset === \"cloudflare-pages\" ||\n    preset === \"cloudflare-module\" ||\n    preset === \"netlify-edge\" ||\n    preset === \"vercel-edge\" ||\n    preset === \"deno\"\n  ) {\n    return \"edge\";\n  }\n\n  if (\n    preset === \"node-server\" ||\n    preset === \"vercel\" ||\n    preset === \"netlify\" ||\n    preset === \"aws-lambda\" ||\n    preset === \"azure\" ||\n    preset === \"firebase\" ||\n    preset === \"bun\" ||\n    preset === \"self-host\" ||\n    preset === \"farm\"\n  ) {\n    return \"node\";\n  }\n\n  return \"unknown\";\n}\n\nexport interface FarmDeploymentMismatch {\n  clientDeploymentId: string;\n  serverDeploymentId: string;\n}\n\nexport interface FarmDeploymentResponseOptions {\n  setCookie?: boolean;\n  cookiePath?: string;\n  secureCookie?: boolean;\n}\n\nexport class FarmDeploymentMismatchError extends Error {\n  readonly name = \"FarmDeploymentMismatchError\";\n  readonly code = FARM_DEPLOYMENT_MISMATCH_CODE;\n  readonly retryable = false;\n\n  constructor(\n    readonly clientDeploymentId: string,\n    readonly serverDeploymentId: string,\n  ) {\n    super(\"The application was updated while this page was open. Refresh before trying again.\");\n  }\n}\n\nexport function normalizeFarmDeploymentId(value: unknown): string {\n  if (typeof value !== \"string\" || value.trim() === \"\") {\n    throw new TypeError(\"Farm deploymentId must be a non-empty string\");\n  }\n\n  const normalized = value.trim();\n  if (normalized.length > 200 || /[\\u0000-\\u001f\\u007f]/.test(normalized)) {\n    throw new TypeError(\"Farm deploymentId must be at most 200 characters without control bytes\");\n  }\n\n  return normalized;\n}\n\nexport function createFarmDeploymentRequestHeaders(\n  deploymentId: string | undefined,\n  init?: HeadersInit,\n): Headers {\n  const headers = new Headers(init);\n  if (deploymentId) {\n    headers.set(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n  }\n  return headers;\n}\n\nexport function getFarmRequestDeploymentId(\n  request: Pick<Request, \"headers\" | \"method\">,\n): string | undefined {\n  const headerValue = request.headers.get(FARM_DEPLOYMENT_ID_HEADER)?.trim();\n  if (headerValue) return headerValue;\n\n  if (isSafeRequestMethod(request.method)) return undefined;\n  return readCookie(request.headers.get(\"cookie\"), FARM_DEPLOYMENT_COOKIE);\n}\n\nexport function getFarmDeploymentMismatch(\n  request: Pick<Request, \"headers\" | \"method\">,\n  serverDeploymentId: string | undefined,\n): FarmDeploymentMismatch | null {\n  if (!serverDeploymentId) return null;\n\n  const clientDeploymentId = getFarmRequestDeploymentId(request);\n  if (!clientDeploymentId || clientDeploymentId === serverDeploymentId) return null;\n\n  return { clientDeploymentId, serverDeploymentId };\n}\n\nexport function createFarmDeploymentMismatchResponse(mismatch: FarmDeploymentMismatch): Response {\n  return new Response(\n    JSON.stringify({\n      error: FARM_DEPLOYMENT_MISMATCH_CODE,\n      message: \"The application deployment changed. Refresh before retrying this request.\",\n    }),\n    {\n      status: FARM_DEPLOYMENT_MISMATCH_STATUS,\n      headers: {\n        \"Cache-Control\": \"no-store\",\n        \"Content-Type\": \"application/json; charset=utf-8\",\n        [FARM_DEPLOYMENT_ID_HEADER]: mismatch.serverDeploymentId,\n        [FARM_DEPLOYMENT_MISMATCH_HEADER]: \"1\",\n      },\n    },\n  );\n}\n\nexport function withFarmDeploymentResponse(\n  response: Response,\n  deploymentId: string | undefined,\n  options: FarmDeploymentResponseOptions = {},\n): Response {\n  if (!deploymentId) return response;\n\n  const headers = new Headers(response.headers);\n  headers.set(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n  if (options.setCookie) {\n    headers.append(\n      \"Set-Cookie\",\n      createFarmDeploymentCookie(\n        deploymentId,\n        options.cookiePath ?? \"/\",\n        options.secureCookie ?? false,\n      ),\n    );\n  }\n\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function getFarmResponseDeploymentId(\n  response: Pick<Response, \"headers\">,\n): string | undefined {\n  return response.headers.get(FARM_DEPLOYMENT_ID_HEADER)?.trim() || undefined;\n}\n\nexport function isFarmDeploymentMismatchResponse(\n  response: Pick<Response, \"headers\" | \"status\">,\n  clientDeploymentId: string | undefined,\n): boolean {\n  const serverDeploymentId = getFarmResponseDeploymentId(response);\n  if (clientDeploymentId && serverDeploymentId && clientDeploymentId !== serverDeploymentId) {\n    return true;\n  }\n\n  return (\n    response.status === FARM_DEPLOYMENT_MISMATCH_STATUS &&\n    response.headers.get(FARM_DEPLOYMENT_MISMATCH_HEADER) === \"1\"\n  );\n}\n\nexport function createFarmDeploymentMismatchError(\n  response: Pick<Response, \"headers\">,\n  clientDeploymentId: string,\n): FarmDeploymentMismatchError {\n  return new FarmDeploymentMismatchError(\n    clientDeploymentId,\n    getFarmResponseDeploymentId(response) || \"unknown\",\n  );\n}\n\nexport function createFarmDeploymentCookie(\n  deploymentId: string,\n  path = \"/\",\n  secure = false,\n): string {\n  const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n  return [\n    `${FARM_DEPLOYMENT_COOKIE}=${encodeURIComponent(deploymentId)}`,\n    `Path=${normalizedPath}`,\n    \"HttpOnly\",\n    \"SameSite=Lax\",\n    secure ? \"Secure\" : \"\",\n  ]\n    .filter(Boolean)\n    .join(\"; \");\n}\n\nfunction readCookie(cookieHeader: string | null, name: string): string | undefined {\n  if (!cookieHeader) return undefined;\n\n  for (const part of cookieHeader.split(\";\")) {\n    const separator = part.indexOf(\"=\");\n    if (separator === -1 || part.slice(0, separator).trim() !== name) continue;\n\n    const value = part.slice(separator + 1).trim();\n    try {\n      return decodeURIComponent(value);\n    } catch {\n      return value;\n    }\n  }\n\n  return undefined;\n}\n\nfunction isSafeRequestMethod(method: string): boolean {\n  return [\"GET\", \"HEAD\", \"OPTIONS\", \"QUERY\"].includes(method.toUpperCase());\n}\n","export const DEFAULT_FARM_DEVTOOLS_SHORTCUT = \"mod+shift+.\";\nexport const FARM_DEVTOOLS_PATH = \"/__farm/devtools\";\nexport const FARM_DEVTOOLS_LAUNCH_PARAM = \"__farm_devtools\";\n\n/**\n * Configuration for the built-in DevTools dashboard. The dashboard is deprecated in favor\n * of the `@farm.js/devtools` plugin, which reuses this configuration for enablement and\n * the keyboard shortcut. Both options keep working while the built-in UI remains available.\n */\nexport interface FarmDevtoolsConfig {\n  /** Enable the development-only DevTools UI and runtime endpoints. */\n  enabled?: boolean;\n  /** Keyboard shortcut used to toggle DevTools, or false to disable the shortcut. */\n  shortcut?: string | false;\n}\n\nexport type FarmDevtoolsUserConfig = boolean | FarmDevtoolsConfig;\n\nexport interface ResolvedFarmDevtoolsConfig {\n  enabled: boolean;\n  shortcut: string | false;\n}\n\nexport function resolveFarmDevtoolsConfig(\n  config: FarmDevtoolsUserConfig | ResolvedFarmDevtoolsConfig | undefined,\n  mode: \"development\" | \"production\" = \"development\",\n): ResolvedFarmDevtoolsConfig {\n  if (mode !== \"development\" || config === false) {\n    return { enabled: false, shortcut: false };\n  }\n\n  const options = config === true || config === undefined ? {} : config;\n  const enabled = options.enabled ?? true;\n\n  if (!enabled) {\n    return { enabled: false, shortcut: false };\n  }\n\n  const shortcut =\n    typeof options.shortcut === \"string\" && options.shortcut.trim()\n      ? options.shortcut\n          .toLowerCase()\n          .split(\"+\")\n          .map((part) => part.trim())\n          .filter(Boolean)\n          .join(\"+\")\n      : options.shortcut === false\n        ? false\n        : DEFAULT_FARM_DEVTOOLS_SHORTCUT;\n\n  return { enabled: true, shortcut };\n}\n","export type FarmBuildActivityPosition = \"bottom-right\" | \"bottom-left\" | \"top-right\" | \"top-left\";\n\nexport interface FarmDevIndicatorsConfig {\n  /** Show build and HMR activity in the browser during development. */\n  buildActivity?: boolean;\n  /** Corner used by the build activity indicator. */\n  buildActivityPosition?: FarmBuildActivityPosition;\n}\n\nexport interface ResolvedFarmDevIndicatorsConfig {\n  buildActivity: boolean;\n  buildActivityPosition: FarmBuildActivityPosition;\n}\n\nexport function resolveFarmDevIndicatorsConfig(\n  config: FarmDevIndicatorsConfig | undefined,\n  mode: \"development\" | \"production\" = \"development\",\n): ResolvedFarmDevIndicatorsConfig {\n  return {\n    buildActivity: mode === \"development\" && (config?.buildActivity ?? true),\n    buildActivityPosition: config?.buildActivityPosition ?? \"bottom-right\",\n  };\n}\n\nexport function generateFarmDevIndicatorsClientRuntime(\n  config: ResolvedFarmDevIndicatorsConfig,\n): string {\n  if (!config.buildActivity) return \"\";\n\n  const position = {\n    \"bottom-right\": \"right: 16px; bottom: 16px;\",\n    \"bottom-left\": \"left: 16px; bottom: 16px;\",\n    \"top-right\": \"right: 16px; top: 16px;\",\n    \"top-left\": \"left: 16px; top: 16px;\",\n  }[config.buildActivityPosition];\n  const styles = `\n    #__farm_build_activity__ {\n      position: fixed;\n      ${position}\n      z-index: 2147483645;\n      display: inline-flex;\n      align-items: center;\n      gap: 7px;\n      min-height: 30px;\n      padding: 0 10px;\n      border: 1px solid rgb(255 255 255 / 0.16);\n      border-radius: 999px;\n      background: rgb(17 17 17 / 0.9);\n      box-shadow: 0 8px 24px rgb(0 0 0 / 0.2);\n      color: rgb(250 250 250);\n      font: 500 12px/1 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n      letter-spacing: -0.01em;\n      opacity: 0;\n      pointer-events: none;\n      transform: translateY(4px);\n      transition: opacity 120ms ease-out, transform 120ms ease-out;\n    }\n    #__farm_build_activity__[data-visible=\"true\"] {\n      opacity: 1;\n      transform: translateY(0);\n    }\n    #__farm_build_activity__::before {\n      width: 8px;\n      height: 8px;\n      border: 1.5px solid rgb(255 255 255 / 0.32);\n      border-top-color: currentColor;\n      border-radius: 50%;\n      content: \"\";\n      animation: farm-build-activity-spin 650ms linear infinite;\n    }\n    #__farm_build_activity__[data-state=\"ready\"]::before {\n      border-color: currentColor;\n      animation: none;\n    }\n    #__farm_build_activity__[data-state=\"error\"] {\n      border-color: rgb(248 113 113 / 0.55);\n      color: rgb(254 202 202);\n    }\n    #__farm_build_activity__[data-state=\"error\"]::before {\n      border-color: currentColor;\n      animation: none;\n    }\n    @keyframes farm-build-activity-spin { to { transform: rotate(360deg); } }\n    @media (prefers-reduced-motion: reduce) {\n      #__farm_build_activity__ { transition: none; }\n      #__farm_build_activity__::before { animation-duration: 1.4s; }\n    }\n  `;\n\n  return `\nif (import.meta.hot) {\n  (() => {\n    const hot = import.meta.hot;\n    const indicatorId = \"__farm_build_activity__\";\n    const styleId = \"__farm_build_activity_styles__\";\n    const runtimeKey = \"__FARM_BUILD_ACTIVITY_RUNTIME__\";\n    const reloadMarker = \"__FARM_BUILD_ACTIVITY_RELOADING__\";\n    let hideTimer;\n\n    const ensureIndicator = () => {\n      let style = document.getElementById(styleId);\n      if (!style) {\n        style = document.createElement(\"style\");\n        style.id = styleId;\n        style.textContent = ${JSON.stringify(styles)};\n        document.head.appendChild(style);\n      }\n\n      let indicator = document.getElementById(indicatorId);\n      if (!indicator) {\n        indicator = document.createElement(\"div\");\n        indicator.id = indicatorId;\n        indicator.setAttribute(\"role\", \"status\");\n        indicator.setAttribute(\"aria-live\", \"polite\");\n        document.body.appendChild(indicator);\n      }\n      return indicator;\n    };\n\n    const show = (state, label) => {\n      window.clearTimeout(hideTimer);\n      const indicator = ensureIndicator();\n      indicator.dataset.state = state;\n      indicator.dataset.visible = \"true\";\n      indicator.textContent = label;\n    };\n    const hide = () => {\n      const indicator = document.getElementById(indicatorId);\n      if (indicator) indicator.dataset.visible = \"false\";\n    };\n    const onBeforeUpdate = () => show(\"building\", \"Farm updating\");\n    const onAfterUpdate = () => {\n      show(\"ready\", \"Farm ready\");\n      hideTimer = window.setTimeout(hide, 500);\n    };\n    const onError = () => show(\"error\", \"Build failed\");\n    const onBeforeFullReload = () => {\n      try {\n        window.sessionStorage.setItem(reloadMarker, \"1\");\n      } catch {}\n      show(\"building\", \"Farm updating\");\n    };\n\n    window[runtimeKey]?.dispose?.();\n    ensureIndicator();\n    let completedReload = false;\n    try {\n      completedReload = window.sessionStorage.getItem(reloadMarker) === \"1\";\n      window.sessionStorage.removeItem(reloadMarker);\n    } catch {}\n    if (completedReload) onAfterUpdate();\n    else hide();\n    hot.on(\"vite:beforeUpdate\", onBeforeUpdate);\n    hot.on(\"vite:afterUpdate\", onAfterUpdate);\n    hot.on(\"vite:error\", onError);\n    hot.on(\"vite:beforeFullReload\", onBeforeFullReload);\n    window[runtimeKey] = {\n      dispose() {\n        window.clearTimeout(hideTimer);\n        hot.off(\"vite:beforeUpdate\", onBeforeUpdate);\n        hot.off(\"vite:afterUpdate\", onAfterUpdate);\n        hot.off(\"vite:error\", onError);\n        hot.off(\"vite:beforeFullReload\", onBeforeFullReload);\n        document.getElementById(indicatorId)?.remove();\n      },\n    };\n  })();\n}\n`;\n}\n","export const DEFAULT_FARM_IMAGE_PATH = \"/_farm/image\";\nexport const DEFAULT_FARM_IMAGE_DEVICE_SIZES = [\n  640, 750, 828, 1080, 1200, 1920, 2048, 3840,\n] as const;\nexport const DEFAULT_FARM_IMAGE_SIZES = [16, 32, 48, 64, 96, 128, 256, 384] as const;\nexport const DEFAULT_FARM_IMAGE_QUALITIES = [75] as const;\nexport const DEFAULT_FARM_IMAGE_FORMATS = [\"image/webp\"] as const;\n\nexport type FarmImageFormat = \"image/avif\" | \"image/webp\";\nexport type FarmImageProvider = \"auto\" | \"node\" | \"cloudflare\" | \"none\";\n\nexport interface FarmImageRemotePattern {\n  protocol?: \"http\" | \"https\";\n  hostname: string;\n  port?: string;\n  pathname?: string;\n  search?: string;\n}\n\nexport interface FarmImageLocalPattern {\n  pathname: string;\n  search?: string;\n}\n\nexport interface FarmImageConfig {\n  /** Runtime optimizer. Auto selects Cloudflare Images on Cloudflare and Sharp elsewhere. */\n  provider?: FarmImageProvider;\n  /** Public optimizer endpoint. */\n  path?: string;\n  /** @deprecated Prefer remotePatterns, which also restricts protocol, path, port, and query. */\n  domains?: readonly string[];\n  remotePatterns?: readonly FarmImageRemotePattern[];\n  localPatterns?: readonly FarmImageLocalPattern[];\n  deviceSizes?: readonly number[];\n  imageSizes?: readonly number[];\n  qualities?: readonly number[];\n  formats?: readonly FarmImageFormat[];\n  minimumCacheTTL?: number;\n  maximumResponseBody?: number | string;\n  maximumRedirects?: number;\n  dangerouslyAllowSVG?: boolean;\n  dangerouslyAllowLocalIP?: boolean;\n}\n\nexport interface ResolvedFarmImageConfig {\n  provider: FarmImageProvider;\n  path: string;\n  domains: readonly string[];\n  remotePatterns: readonly FarmImageRemotePattern[];\n  localPatterns: readonly FarmImageLocalPattern[];\n  deviceSizes: readonly number[];\n  imageSizes: readonly number[];\n  qualities: readonly number[];\n  formats: readonly FarmImageFormat[];\n  minimumCacheTTL: number;\n  maximumResponseBody: number;\n  maximumRedirects: number;\n  dangerouslyAllowSVG: boolean;\n  dangerouslyAllowLocalIP: boolean;\n}\n\nexport type PublicFarmImageConfig = Pick<\n  ResolvedFarmImageConfig,\n  \"provider\" | \"path\" | \"deviceSizes\" | \"imageSizes\" | \"qualities\" | \"formats\"\n>;\n\nconst SIZE_UNITS: Record<string, number> = {\n  b: 1,\n  kb: 1_000,\n  mb: 1_000_000,\n  gb: 1_000_000_000,\n  kib: 1_024,\n  mib: 1_048_576,\n  gib: 1_073_741_824,\n};\n\nexport function resolveFarmImageConfig(\n  config: FarmImageConfig | undefined,\n): ResolvedFarmImageConfig {\n  const path = normalizeImagePath(config?.path ?? DEFAULT_FARM_IMAGE_PATH);\n  const deviceSizes = normalizeIntegerList(\n    config?.deviceSizes ?? DEFAULT_FARM_IMAGE_DEVICE_SIZES,\n    \"images.deviceSizes\",\n  );\n  const imageSizes = normalizeIntegerList(\n    config?.imageSizes ?? DEFAULT_FARM_IMAGE_SIZES,\n    \"images.imageSizes\",\n  );\n  const qualities = normalizeIntegerList(\n    config?.qualities ?? DEFAULT_FARM_IMAGE_QUALITIES,\n    \"images.qualities\",\n    100,\n  );\n  const formats = [...new Set(config?.formats ?? DEFAULT_FARM_IMAGE_FORMATS)];\n\n  if (formats.some((format) => format !== \"image/avif\" && format !== \"image/webp\")) {\n    throw new TypeError('images.formats only supports \"image/avif\" and \"image/webp\"');\n  }\n\n  const minimumCacheTTL = normalizeNonNegativeInteger(\n    config?.minimumCacheTTL ?? 60,\n    \"images.minimumCacheTTL\",\n  );\n  const maximumRedirects = normalizeNonNegativeInteger(\n    config?.maximumRedirects ?? 3,\n    \"images.maximumRedirects\",\n  );\n\n  return Object.freeze({\n    provider: config?.provider ?? \"auto\",\n    path,\n    domains: Object.freeze([\n      ...new Set(\n        (config?.domains ?? []).map((domain) => domain.trim().toLowerCase()).filter(Boolean),\n      ),\n    ]),\n    remotePatterns: Object.freeze(\n      (config?.remotePatterns ?? []).map((pattern) => normalizeRemotePattern(pattern)),\n    ),\n    localPatterns: Object.freeze(\n      (config?.localPatterns ?? [{ pathname: \"/**\" }]).map((pattern) =>\n        normalizeLocalPattern(pattern),\n      ),\n    ),\n    deviceSizes: Object.freeze(deviceSizes),\n    imageSizes: Object.freeze(imageSizes),\n    qualities: Object.freeze(qualities),\n    formats: Object.freeze(formats),\n    minimumCacheTTL,\n    maximumResponseBody: parseSize(\n      config?.maximumResponseBody ?? \"10mb\",\n      \"images.maximumResponseBody\",\n    ),\n    maximumRedirects,\n    dangerouslyAllowSVG: config?.dangerouslyAllowSVG ?? false,\n    dangerouslyAllowLocalIP: config?.dangerouslyAllowLocalIP ?? false,\n  });\n}\n\nexport function getPublicFarmImageConfig(\n  config: Pick<ResolvedFarmImageConfig, keyof PublicFarmImageConfig>,\n): PublicFarmImageConfig {\n  return {\n    provider: config.provider,\n    path: config.path,\n    deviceSizes: config.deviceSizes,\n    imageSizes: config.imageSizes,\n    qualities: config.qualities,\n    formats: config.formats,\n  };\n}\n\nfunction normalizeImagePath(value: string): string {\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(value)) {\n    throw new TypeError(\"images.path cannot contain backslashes or control characters\");\n  }\n\n  const path = value.trim().replace(/\\/+$/, \"\") || \"/\";\n  if (!path.startsWith(\"/\") || path.startsWith(\"//\") || path.includes(\"?\") || path.includes(\"#\")) {\n    throw new TypeError(\"images.path must be an absolute pathname without a query or hash\");\n  }\n\n  for (const segment of path.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal and cannot conceal a path separator\n      // or dot segment.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new TypeError(\"images.path cannot contain backslashes or control characters\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new TypeError(\"images.path cannot contain percent-encoded path separators\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new TypeError('images.path cannot contain \".\" or \"..\" path segments');\n    }\n  }\n\n  return path;\n}\n\nfunction normalizeIntegerList(values: readonly number[], name: string, max?: number): number[] {\n  if (values.length === 0) {\n    throw new TypeError(`${name} must contain at least one value`);\n  }\n\n  const normalized = [...new Set(values)].sort((left, right) => left - right);\n  for (const value of normalized) {\n    if (!Number.isSafeInteger(value) || value <= 0 || (max !== undefined && value > max)) {\n      throw new TypeError(\n        `${name} must contain positive integers${max ? ` no greater than ${max}` : \"\"}`,\n      );\n    }\n  }\n  return normalized;\n}\n\nfunction normalizeNonNegativeInteger(value: number, name: string): number {\n  if (!Number.isSafeInteger(value) || value < 0) {\n    throw new TypeError(`${name} must be a non-negative safe integer`);\n  }\n  return value;\n}\n\nfunction parseSize(value: number | string, name: string): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${name} must be a positive safe integer`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)$/);\n  if (!match) {\n    throw new TypeError(`${name} must be bytes or a size string such as \"5mb\"`);\n  }\n\n  const bytes = Number(match[1]) * SIZE_UNITS[match[2]];\n  if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n    throw new TypeError(`${name} must resolve to a positive safe integer`);\n  }\n  return bytes;\n}\n\nfunction normalizeRemotePattern(pattern: FarmImageRemotePattern): FarmImageRemotePattern {\n  const hostname = pattern.hostname.trim().toLowerCase();\n  if (!hostname || hostname.includes(\"/\") || hostname.includes(\":\")) {\n    throw new TypeError(\"images.remotePatterns[].hostname must be a hostname or wildcard hostname\");\n  }\n  if (pattern.pathname && !pattern.pathname.startsWith(\"/\")) {\n    throw new TypeError(\"images.remotePatterns[].pathname must start with /\");\n  }\n  if (pattern.search && !pattern.search.startsWith(\"?\")) {\n    throw new TypeError(\"images.remotePatterns[].search must start with ?\");\n  }\n  return Object.freeze({ ...pattern, hostname });\n}\n\nfunction normalizeLocalPattern(pattern: FarmImageLocalPattern): FarmImageLocalPattern {\n  if (!pattern.pathname.startsWith(\"/\")) {\n    throw new TypeError(\"images.localPatterns[].pathname must start with /\");\n  }\n  if (pattern.search && !pattern.search.startsWith(\"?\")) {\n    throw new TypeError(\"images.localPatterns[].search must start with ?\");\n  }\n  return Object.freeze({ ...pattern });\n}\n","import 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","export type FarmPreloadMode = \"warn\" | \"enforce\";\n\nexport interface FarmPreloadUserConfig {\n  /** Report excess hints or remove the lower-priority hints. @default \"enforce\" */\n  mode?: FarmPreloadMode;\n  /** Maximum image preload hints per document. @default 1 */\n  maxImages?: number;\n  /** Maximum font preload hints per document. @default 2 */\n  maxFonts?: number;\n}\n\nexport interface ResolvedFarmPreloadConfig {\n  mode: FarmPreloadMode;\n  maxImages: number;\n  maxFonts: number;\n}\n\nexport interface FarmPerformanceConfig {\n  preload?: FarmPreloadUserConfig;\n}\n\nexport interface ResolvedFarmPerformanceConfig {\n  preload: ResolvedFarmPreloadConfig;\n}\n\nexport type FarmPreloadKind = \"image\" | \"font\";\n\nexport interface FarmPreloadBudgetWarning {\n  kind: FarmPreloadKind;\n  count: number;\n  budget: number;\n  removed: number;\n}\n\nexport interface FarmManagedPreloads {\n  value: string;\n  warnings: FarmPreloadBudgetWarning[];\n}\n\nexport interface FarmManagedDocumentPreloads {\n  html: string;\n  linkHeader: string;\n  warnings: FarmPreloadBudgetWarning[];\n}\n\nconst DEFAULT_PRELOAD_CONFIG: ResolvedFarmPreloadConfig = {\n  mode: \"enforce\",\n  maxImages: 1,\n  maxFonts: 2,\n};\n\nconst reportedWarnings = new Map<string, number>();\nconst PRELOAD_WARNING_TTL_MS = 60_000;\nconst MAX_REPORTED_PRELOAD_WARNINGS = 256;\n\nexport function resolveFarmPerformanceConfig(\n  config: FarmPerformanceConfig | undefined,\n): ResolvedFarmPerformanceConfig {\n  return {\n    preload: {\n      mode: config?.preload?.mode === \"warn\" ? \"warn\" : \"enforce\",\n      maxImages: normalizeBudget(config?.preload?.maxImages, DEFAULT_PRELOAD_CONFIG.maxImages),\n      maxFonts: normalizeBudget(config?.preload?.maxFonts, DEFAULT_PRELOAD_CONFIG.maxFonts),\n    },\n  };\n}\n\n/**\n * Apply image and font budgets to HTML preload elements. High-priority image\n * hints are retained before ordinary hints, making an explicitly preloaded LCP\n * image the winner when a document contains too many React-generated hints.\n */\nexport function manageFarmHtmlPreloads(\n  html: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedPreloads {\n  const elements = findHtmlLinkElements(html);\n  const candidates = elements.flatMap((element, index) => {\n    const kind = getHtmlPreloadKind(element.value);\n    return kind\n      ? [\n          {\n            index,\n            kind,\n            highPriority:\n              readHtmlAttribute(element.value, \"fetchpriority\")?.toLowerCase() === \"high\",\n          },\n        ]\n      : [];\n  });\n\n  const budget = selectPreloadsWithinBudget(candidates, config);\n  if (config.mode === \"warn\" || budget.removed.size === 0) {\n    return { value: html, warnings: budget.warnings };\n  }\n\n  return {\n    value: removeHtmlLinkElements(html, elements, budget.removed),\n    warnings: budget.warnings,\n  };\n}\n\n/** Apply the same budgets to HTTP Link preload hints, including Farm fonts. */\nexport function manageFarmLinkHeaderPreloads(\n  value: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedPreloads {\n  if (!value) return { value, warnings: [] };\n\n  const links = splitLinkHeader(value);\n  const candidates = links.flatMap((link, index) => {\n    const kind = getLinkHeaderPreloadKind(link);\n    return kind\n      ? [\n          {\n            index,\n            kind,\n            highPriority: getLinkHeaderParameter(link, \"fetchpriority\")?.toLowerCase() === \"high\",\n          },\n        ]\n      : [];\n  });\n  const budget = selectPreloadsWithinBudget(candidates, config);\n\n  return {\n    value:\n      config.mode === \"enforce\"\n        ? links.filter((_, index) => !budget.removed.has(index)).join(\", \")\n        : value,\n    warnings: budget.warnings,\n  };\n}\n\n/** Apply a single document budget across HTML and HTTP Link header hints. */\nexport function manageFarmDocumentPreloads(\n  html: string,\n  linkHeader: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedDocumentPreloads {\n  const elements = findHtmlLinkElements(html);\n  const links = linkHeader ? splitLinkHeader(linkHeader) : [];\n  const headerOffset = elements.length;\n  const candidates: PreloadCandidate[] = [];\n\n  for (const [index, element] of elements.entries()) {\n    const kind = getHtmlPreloadKind(element.value);\n    if (!kind) continue;\n    candidates.push({\n      index,\n      kind,\n      highPriority: readHtmlAttribute(element.value, \"fetchpriority\")?.toLowerCase() === \"high\",\n    });\n  }\n  for (const [index, link] of links.entries()) {\n    const kind = getLinkHeaderPreloadKind(link);\n    if (!kind) continue;\n    candidates.push({\n      index: headerOffset + index,\n      kind,\n      highPriority: getLinkHeaderParameter(link, \"fetchpriority\")?.toLowerCase() === \"high\",\n    });\n  }\n\n  const budget = selectPreloadsWithinBudget(candidates, config);\n  if (config.mode === \"warn\" || budget.removed.size === 0) {\n    return { html, linkHeader, warnings: budget.warnings };\n  }\n\n  return {\n    html: removeHtmlLinkElements(html, elements, budget.removed),\n    linkHeader: links.filter((_, index) => !budget.removed.has(headerOffset + index)).join(\", \"),\n    warnings: budget.warnings,\n  };\n}\n\n/** Rate-limit identical route-and-budget warnings within a server process. */\nexport function reportFarmPreloadWarnings(\n  warnings: FarmPreloadBudgetWarning[],\n  context = \"the rendered document\",\n): void {\n  const now = Date.now();\n  for (const [key, reportedAt] of reportedWarnings) {\n    if (now - reportedAt >= PRELOAD_WARNING_TTL_MS) reportedWarnings.delete(key);\n  }\n\n  for (const warning of warnings) {\n    const key = `${context}:${warning.kind}:${warning.count}:${warning.budget}:${warning.removed}`;\n    const reportedAt = reportedWarnings.get(key);\n    if (reportedAt !== undefined && now - reportedAt < PRELOAD_WARNING_TTL_MS) continue;\n    reportedWarnings.set(key, now);\n    while (reportedWarnings.size > MAX_REPORTED_PRELOAD_WARNINGS) {\n      const oldest = reportedWarnings.keys().next().value;\n      if (oldest === undefined) break;\n      reportedWarnings.delete(oldest);\n    }\n\n    const action = warning.removed > 0 ? ` Removed ${warning.removed} lower-priority hint(s).` : \"\";\n    const recommendation =\n      warning.kind === \"image\"\n        ? ' Mark only the LCP image with `preload` or `fetchPriority=\"high\"`.'\n        : \" Set `preload: false` on fonts that are not required above the fold.\";\n    console.warn(\n      `[Farm.js] ${context} emitted ${warning.count} ${warning.kind} preload hints ` +\n        `(budget: ${warning.budget}).${action}${recommendation}`,\n    );\n  }\n}\n\nexport function clearReportedFarmPreloadWarnings(): void {\n  reportedWarnings.clear();\n}\n\ninterface PreloadCandidate {\n  index: number;\n  kind: FarmPreloadKind;\n  highPriority: boolean;\n}\n\nfunction selectPreloadsWithinBudget(\n  candidates: PreloadCandidate[],\n  config: ResolvedFarmPreloadConfig,\n): { removed: Set<number>; warnings: FarmPreloadBudgetWarning[] } {\n  const removed = new Set<number>();\n  const warnings: FarmPreloadBudgetWarning[] = [];\n\n  for (const kind of [\"image\", \"font\"] as const) {\n    const matching = candidates.filter((candidate) => candidate.kind === kind);\n    const limit = kind === \"image\" ? config.maxImages : config.maxFonts;\n    if (matching.length <= limit) continue;\n\n    const retained = new Set(\n      [...matching]\n        .sort(\n          (left, right) =>\n            Number(right.highPriority) - Number(left.highPriority) || left.index - right.index,\n        )\n        .slice(0, limit)\n        .map((candidate) => candidate.index),\n    );\n\n    if (config.mode === \"enforce\") {\n      for (const candidate of matching) {\n        if (!retained.has(candidate.index)) removed.add(candidate.index);\n      }\n    }\n\n    warnings.push({\n      kind,\n      count: matching.length,\n      budget: limit,\n      removed: config.mode === \"enforce\" ? matching.length - retained.size : 0,\n    });\n  }\n\n  return { removed, warnings };\n}\n\nfunction getHtmlPreloadKind(link: string): FarmPreloadKind | undefined {\n  const rel = readHtmlAttribute(link, \"rel\")?.toLowerCase().split(/\\s+/) || [];\n  if (!rel.includes(\"preload\")) return undefined;\n  return normalizePreloadKind(readHtmlAttribute(link, \"as\"));\n}\n\nfunction getLinkHeaderPreloadKind(link: string): FarmPreloadKind | undefined {\n  const relations = getLinkHeaderParameter(link, \"rel\")?.toLowerCase().split(/\\s+/) ?? [];\n  if (!relations.includes(\"preload\")) return undefined;\n  return normalizePreloadKind(getLinkHeaderParameter(link, \"as\"));\n}\n\nfunction getLinkHeaderParameter(link: string, name: string): string | undefined {\n  const uriEnd = link.indexOf(\">\");\n  if (uriEnd === -1) return undefined;\n\n  for (const parameter of splitLinkParameters(link.slice(uriEnd + 1))) {\n    const separator = parameter.indexOf(\"=\");\n    const parameterName = (separator === -1 ? parameter : parameter.slice(0, separator))\n      .trim()\n      .toLowerCase();\n    if (parameterName !== name.toLowerCase() || separator === -1) continue;\n    const rawValue = parameter.slice(separator + 1).trim();\n    if (rawValue.startsWith('\"') && rawValue.endsWith('\"')) {\n      return rawValue.slice(1, -1).replace(/\\\\([\\\\\"])/g, \"$1\");\n    }\n    return rawValue;\n  }\n  return undefined;\n}\n\nfunction splitLinkParameters(value: string): string[] {\n  const parameters: string[] = [];\n  let start = 0;\n  let quoted = false;\n  for (let index = 0; index < value.length; index += 1) {\n    const character = value[index];\n    if (character === '\"' && !isEscaped(value, index)) quoted = !quoted;\n    else if (character === \";\" && !quoted) {\n      const parameter = value.slice(start, index).trim();\n      if (parameter) parameters.push(parameter);\n      start = index + 1;\n    }\n  }\n  const parameter = value.slice(start).trim();\n  if (parameter) parameters.push(parameter);\n  return parameters;\n}\n\nfunction normalizePreloadKind(value: string | undefined): FarmPreloadKind | undefined {\n  const normalized = value?.toLowerCase();\n  return normalized === \"image\" || normalized === \"font\" ? normalized : undefined;\n}\n\nfunction readHtmlAttribute(element: string, name: string): string | undefined {\n  const match = element.match(\n    new RegExp(`\\\\s${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s>]+))`, \"i\"),\n  );\n  return match?.[1] ?? match?.[2] ?? match?.[3];\n}\n\ninterface HtmlLinkElement {\n  start: number;\n  end: number;\n  value: string;\n}\n\nfunction findHtmlLinkElements(html: string): HtmlLinkElement[] {\n  const elements: HtmlLinkElement[] = [];\n  const lowerHtml = html.toLowerCase();\n  let cursor = 0;\n\n  while (cursor < html.length) {\n    const start = html.indexOf(\"<\", cursor);\n    if (start === -1) break;\n\n    if (lowerHtml.startsWith(\"<!--\", start)) {\n      const commentEnd = lowerHtml.indexOf(\"-->\", start + 4);\n      cursor = commentEnd === -1 ? html.length : commentEnd + 3;\n      continue;\n    }\n\n    const rawText = lowerHtml\n      .slice(start)\n      .match(/^<(script|style|template|textarea|title|noscript|svg)(?=[\\s/>])/);\n    if (rawText?.[1]) {\n      const openingEnd = findHtmlTagEnd(html, start);\n      if (openingEnd === -1) break;\n      if (rawText[1] === \"svg\" && html[openingEnd - 2] === \"/\") {\n        cursor = openingEnd;\n        continue;\n      }\n      const closingStart = findHtmlClosingTag(lowerHtml, rawText[1], openingEnd);\n      if (closingStart === -1) {\n        cursor = html.length;\n        continue;\n      }\n      const closingEnd = findHtmlTagEnd(html, closingStart);\n      cursor = closingEnd === -1 ? html.length : closingEnd;\n      continue;\n    }\n\n    if (/^<link(?=[\\s/>])/i.test(html.slice(start))) {\n      const end = findHtmlTagEnd(html, start);\n      if (end === -1) break;\n      elements.push({ start, end, value: html.slice(start, end) });\n      cursor = end;\n      continue;\n    }\n\n    if (/^<\\/?[A-Za-z][\\w:-]*(?=[\\s/>])/.test(html.slice(start))) {\n      const end = findHtmlTagEnd(html, start);\n      cursor = end === -1 ? html.length : end;\n      continue;\n    }\n\n    cursor = start + 1;\n  }\n\n  return elements;\n}\n\nfunction findHtmlClosingTag(html: string, tagName: string, start: number): number {\n  const prefix = `</${tagName}`;\n  let candidate = html.indexOf(prefix, start);\n  while (candidate !== -1) {\n    const boundary = html[candidate + prefix.length];\n    if (boundary === \">\" || boundary === \"/\" || /\\s/.test(boundary ?? \"\")) return candidate;\n    candidate = html.indexOf(prefix, candidate + prefix.length);\n  }\n  return -1;\n}\n\nfunction findHtmlTagEnd(html: string, start: number): number {\n  let quote: '\"' | \"'\" | undefined;\n  for (let index = start + 1; index < html.length; index += 1) {\n    const character = html[index];\n    if (quote) {\n      if (character === quote) quote = undefined;\n    } else if (character === '\"' || character === \"'\") {\n      quote = character;\n    } else if (character === \">\") {\n      return index + 1;\n    }\n  }\n  return -1;\n}\n\nfunction removeHtmlLinkElements(\n  html: string,\n  elements: HtmlLinkElement[],\n  removed: ReadonlySet<number>,\n): string {\n  let cursor = 0;\n  let output = \"\";\n  for (const [index, element] of elements.entries()) {\n    if (!removed.has(index)) continue;\n    output += html.slice(cursor, element.start);\n    cursor = element.end;\n  }\n  return output + html.slice(cursor);\n}\n\nfunction splitLinkHeader(value: string): string[] {\n  const links: string[] = [];\n  let start = 0;\n  let insideAngleBrackets = false;\n  let quoted = false;\n\n  for (let index = 0; index < value.length; index += 1) {\n    const character = value[index];\n    if (quoted) {\n      if (character === '\"' && !isEscaped(value, index)) quoted = false;\n      continue;\n    }\n    if (character === '\"') {\n      quoted = true;\n    } else if (character === \"<\") {\n      insideAngleBrackets = true;\n    } else if (character === \">\") {\n      insideAngleBrackets = false;\n    } else if (character === \",\" && !insideAngleBrackets) {\n      links.push(value.slice(start, index).trim());\n      start = index + 1;\n    }\n  }\n\n  links.push(value.slice(start).trim());\n  return links.filter(Boolean);\n}\n\nfunction isEscaped(value: string, index: number): boolean {\n  let backslashes = 0;\n  for (let cursor = index - 1; cursor >= 0 && value[cursor] === \"\\\\\"; cursor -= 1) {\n    backslashes += 1;\n  }\n  return backslashes % 2 === 1;\n}\n\nfunction normalizeBudget(value: number | undefined, fallback: number): number {\n  return typeof value === \"number\" && Number.isFinite(value) && value >= 0\n    ? Math.floor(value)\n    : fallback;\n}\n","export type FarmCspDirectiveValue = string | readonly string[] | boolean | null | undefined;\n\nexport type FarmCspDirectives = Readonly<Record<string, FarmCspDirectiveValue>>;\n\nexport interface FarmCspOptions {\n  /** A pre-serialized CSP value. Cannot be combined with directives. */\n  policy?: string;\n  /** CSP directives using camelCase or kebab-case names. */\n  directives?: FarmCspDirectives;\n  /** Emit Content-Security-Policy-Report-Only instead of enforcing the policy. */\n  reportOnly?: boolean;\n}\n\nexport type FarmCspConfig = string | FarmCspOptions;\n\nexport interface FarmSecurityConfig {\n  /** App-wide Content Security Policy applied to pages, APIs, and static output. */\n  csp?: FarmCspConfig | false;\n  /** @deprecated Use csp. */\n  contentSecurityPolicy?: never;\n}\n\nexport interface ResolvedFarmCspConfig {\n  value: string;\n  reportOnly: boolean;\n}\n\nexport interface ResolvedFarmSecurityConfig {\n  csp: ResolvedFarmCspConfig | false;\n}\n\nexport function resolveFarmSecurityConfig(\n  input: FarmSecurityConfig | ResolvedFarmSecurityConfig | undefined,\n): ResolvedFarmSecurityConfig {\n  if (input === undefined) return { csp: false };\n  if (!isPlainRecord(input)) {\n    throw new TypeError(\"security must be an object containing the csp option.\");\n  }\n  if (Object.prototype.hasOwnProperty.call(input, \"contentSecurityPolicy\")) {\n    throw new TypeError(\n      \"security.contentSecurityPolicy is not supported. Use security.csp instead.\",\n    );\n  }\n\n  const csp = input.csp;\n  if (csp === undefined || csp === false) return { csp: false };\n\n  if (typeof csp === \"string\") {\n    return {\n      csp: {\n        value: validateSerializedCsp(csp),\n        reportOnly: false,\n      },\n    };\n  }\n\n  if (!isPlainRecord(csp)) {\n    throw new TypeError(\"security.csp must be a policy string, false, or an options object.\");\n  }\n\n  const reportOnly = validateReportOnly(csp.reportOnly);\n  if (Object.prototype.hasOwnProperty.call(csp, \"value\")) {\n    if (\n      Object.prototype.hasOwnProperty.call(csp, \"policy\") ||\n      Object.prototype.hasOwnProperty.call(csp, \"directives\")\n    ) {\n      throw new TypeError(\n        \"Resolved security.csp values cannot include policy or directives options.\",\n      );\n    }\n    return {\n      csp: {\n        value: validateSerializedCsp(csp.value),\n        reportOnly,\n      },\n    };\n  }\n\n  const { policy, directives } = csp;\n  if (policy !== undefined && directives !== undefined) {\n    throw new TypeError(\"security.csp accepts either policy or directives, not both.\");\n  }\n  if (policy === undefined && directives === undefined) {\n    throw new TypeError(\"security.csp requires a policy string or directives object.\");\n  }\n\n  return {\n    csp: {\n      value:\n        policy !== undefined\n          ? validateSerializedCsp(policy)\n          : serializeFarmCspDirectives(directives as FarmCspDirectives),\n      reportOnly,\n    },\n  };\n}\n\nexport function serializeFarmCspDirectives(directives: FarmCspDirectives): string {\n  if (!isPlainRecord(directives)) {\n    throw new TypeError(\"security.csp.directives must be an object.\");\n  }\n  const serialized: string[] = [];\n  const normalizedNames = new Set<string>();\n\n  for (const [configuredName, configuredValue] of Object.entries(directives)) {\n    if (configuredValue === false || configuredValue === null || configuredValue === undefined) {\n      continue;\n    }\n\n    const name = normalizeDirectiveName(configuredName);\n    if (normalizedNames.has(name)) {\n      throw new TypeError(`security.csp contains the duplicate directive ${JSON.stringify(name)}.`);\n    }\n    normalizedNames.add(name);\n\n    const values =\n      configuredValue === true\n        ? []\n        : (Array.isArray(configuredValue) ? configuredValue : [configuredValue]).map(\n            validateDirectiveValue,\n          );\n    serialized.push(values.length > 0 ? `${name} ${values.join(\" \")}` : name);\n  }\n\n  if (serialized.length === 0) {\n    throw new TypeError(\"security.csp.directives must contain at least one enabled directive.\");\n  }\n  return serialized.join(\"; \");\n}\n\nexport function getFarmSecurityHeader(\n  security: ResolvedFarmSecurityConfig,\n): { key: string; value: string } | undefined {\n  if (!security.csp) return undefined;\n  return {\n    key: security.csp.reportOnly\n      ? \"Content-Security-Policy-Report-Only\"\n      : \"Content-Security-Policy\",\n    value: security.csp.value,\n  };\n}\n\n/**\n * Whether a resolved CSP would block the inline scripts the framework injects\n * into SSR documents (theme bootstrap, hydration bootstraps).\n *\n * The scripts carry no nonce or hash yet (see the CSP-nonce RFC), so they run\n * only when the governing directive — `script-src`, falling back to\n * `default-src` — permits inline script either via `'unsafe-inline'` or by\n * listing a nonce/hash source. A policy with no script-governing directive at\n * all does not restrict inline scripts, so it is not flagged. When a nonce or\n * hash is already present the app is assumed to be managing inline sources\n * deliberately and is left alone, to avoid nagging a correct-by-construction\n * setup.\n */\nexport function farmCspBlocksFrameworkInlineScripts(security: ResolvedFarmSecurityConfig): boolean {\n  if (!security.csp) return false;\n\n  const directives = parseCspDirectives(security.csp.value);\n  const governing = directives.get(\"script-src\") ?? directives.get(\"default-src\");\n  if (!governing) return false;\n\n  const allowsInline = governing.some((source) => {\n    const value = source.toLowerCase();\n    return (\n      value === \"'unsafe-inline'\" ||\n      value.startsWith(\"'nonce-\") ||\n      value.startsWith(\"'sha256-\") ||\n      value.startsWith(\"'sha384-\") ||\n      value.startsWith(\"'sha512-\")\n    );\n  });\n  return !allowsInline;\n}\n\nfunction parseCspDirectives(value: string): Map<string, string[]> {\n  const directives = new Map<string, string[]>();\n  for (const segment of value.split(\";\")) {\n    const parts = segment.trim().split(/\\s+/).filter(Boolean);\n    if (parts.length === 0) continue;\n    const name = parts[0]!.toLowerCase();\n    if (!directives.has(name)) directives.set(name, parts.slice(1));\n  }\n  return directives;\n}\n\nfunction normalizeDirectiveName(value: string): string {\n  const name = value\n    .trim()\n    .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n    .toLowerCase();\n  if (!/^[a-z][a-z0-9-]*$/.test(name)) {\n    throw new TypeError(`Invalid security.csp directive name: ${JSON.stringify(value)}.`);\n  }\n  return name;\n}\n\nfunction validateDirectiveValue(value: string): string {\n  if (typeof value !== \"string\") {\n    throw new TypeError(\"security.csp directive values must be strings or booleans.\");\n  }\n  const normalized = value.trim();\n  if (!normalized || /[;\\r\\n]/.test(normalized) || normalized.includes(\"\\0\")) {\n    throw new TypeError(`Invalid security.csp directive value: ${JSON.stringify(value)}.`);\n  }\n  return normalized;\n}\n\nfunction validateSerializedCsp(value: unknown): string {\n  if (typeof value !== \"string\") {\n    throw new TypeError(\"security.csp policy must be a non-empty single-line string.\");\n  }\n  const normalized = value.trim().replace(/;+$/g, \"\").trim();\n  if (!normalized || /[\\r\\n]/.test(normalized) || normalized.includes(\"\\0\")) {\n    throw new TypeError(\"security.csp policy must be a non-empty single-line string.\");\n  }\n  return normalized;\n}\n\nfunction validateReportOnly(value: unknown): boolean {\n  if (value === undefined) return false;\n  if (typeof value !== \"boolean\") {\n    throw new TypeError(\"security.csp.reportOnly must be a boolean.\");\n  }\n  return value;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n","import type { FarmThemeConfig, ResolvedFarmThemeConfig } from \"./types\";\n\nexport const DEFAULT_FARM_THEME_STORAGE_KEY = \"farm-theme\";\n\nconst STORAGE_KEY_PATTERN = /^[A-Za-z0-9._-]+$/;\n\nexport function resolveFarmThemeConfig(\n  config: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n): ResolvedFarmThemeConfig {\n  if (config && \"enabled\" in config) {\n    return config;\n  }\n\n  if (!config) {\n    return {\n      enabled: false,\n      default: \"system\",\n      storageKey: DEFAULT_FARM_THEME_STORAGE_KEY,\n      cookiePath: normalizeCookiePath(basePath),\n    };\n  }\n\n  const storageKey = config.storageKey?.trim() || DEFAULT_FARM_THEME_STORAGE_KEY;\n  if (!STORAGE_KEY_PATTERN.test(storageKey)) {\n    throw new Error(\n      \"theme.storageKey may only contain letters, numbers, dots, underscores, and hyphens.\",\n    );\n  }\n\n  const defaultTheme = config.default ?? \"system\";\n  if (defaultTheme !== \"light\" && defaultTheme !== \"dark\" && defaultTheme !== \"system\") {\n    throw new Error('theme.default must be \"light\", \"dark\", or \"system\".');\n  }\n\n  return {\n    enabled: true,\n    default: defaultTheme,\n    storageKey,\n    cookiePath: normalizeCookiePath(basePath),\n  };\n}\n\nfunction normalizeCookiePath(basePath: string): string {\n  const normalized = `/${basePath}`.replace(/\\/{2,}/g, \"/\");\n  if (normalized === \"/\") return normalized;\n  return normalized.replace(/\\/$/, \"\");\n}\n","/**\n * Agent-readiness configuration: opt-in primitives that make a Farm site easier\n * for AI agents and crawlers to discover, resolve, and use. Off by default so\n * sites that do not want agent exposure (internal tools, private dashboards) are\n * unaffected.\n */\n\n/** schema.org JSON-LD emitted in the document head to identify the site. */\nexport interface FarmAgentJsonLd {\n  /**\n   * schema.org `@type`. Common values: `\"Organization\"` for a company or\n   * project, `\"SoftwareApplication\"` for a product, `\"WebSite\"`, `\"Person\"`.\n   *\n   * @default \"Organization\"\n   */\n  type?: string;\n  /** Entity name. Defaults to the site's Open Graph site name or page title. */\n  name?: string;\n  /** Canonical URL for the entity. Defaults to the configured `metadataBase`. */\n  url?: string;\n  /** Short description. Defaults to the page/site metadata description. */\n  description?: string;\n  /** Logo URL. */\n  logo?: string;\n  /** URLs that also represent this entity (social profiles, repos) — schema.org `sameAs`. */\n  sameAs?: string[];\n  /** Additional schema.org properties merged into the emitted object. */\n  properties?: Record<string, unknown>;\n}\n\nexport interface FarmAgentUserConfig {\n  /**\n   * Emit schema.org JSON-LD in the document head so agents and crawlers can\n   * resolve the site's identity. `true` emits an `Organization` built from the\n   * site's metadata; an object customizes the type and fields.\n   *\n   * @default false\n   */\n  jsonLd?: boolean | FarmAgentJsonLd;\n}\n\nexport interface ResolvedFarmAgentConfig {\n  jsonLd: FarmAgentJsonLd | false;\n}\n\nexport function resolveFarmAgentConfig(\n  input: FarmAgentUserConfig | undefined,\n): ResolvedFarmAgentConfig {\n  const jsonLd = input?.jsonLd;\n  if (!jsonLd) return { jsonLd: false };\n  return { jsonLd: jsonLd === true ? {} : jsonLd };\n}\n\nexport interface FarmAgentJsonLdContext {\n  metadataBase?: string;\n  siteName?: string;\n  title?: string;\n  description?: string;\n}\n\nfunction pruneUndefined(object: Record<string, unknown>): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(object)) {\n    if (value !== undefined && value !== null && value !== \"\") result[key] = value;\n  }\n  return result;\n}\n\n/**\n * Serialize a JSON-LD object for inline `<script>` embedding, escaping `<` so a\n * value containing `</script>` cannot break out of the tag.\n */\nfunction serializeJsonLd(value: unknown): string {\n  return JSON.stringify(value).replace(/</g, \"\\\\u003c\");\n}\n\n/**\n * Build a JSON-LD `<script>` tag for the site identity, or an empty string when\n * there is not enough information to emit meaningful structured data.\n */\nexport function renderFarmAgentJsonLd(\n  config: FarmAgentJsonLd,\n  context: FarmAgentJsonLdContext,\n): string {\n  const base = pruneUndefined({\n    name: config.name ?? context.siteName ?? context.title,\n    url: config.url ?? context.metadataBase,\n    description: config.description ?? context.description,\n    logo: config.logo,\n    sameAs: config.sameAs && config.sameAs.length > 0 ? config.sameAs : undefined,\n  });\n\n  const object = {\n    \"@context\": \"https://schema.org\",\n    \"@type\": config.type || \"Organization\",\n    ...base,\n    ...(config.properties || {}),\n  };\n\n  // Nothing beyond @context/@type and no custom properties: not worth emitting.\n  if (Object.keys(object).length <= 2 && !config.properties) {\n    return \"\";\n  }\n\n  return `<script type=\"application/ld+json\">${serializeJsonLd(object)}</script>`;\n}\n","import { 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","import type { ResolvedFarmEnv } from \"../env\";\n\nexport const DEFAULT_FARM_API_BASE_PATH = \"/api\";\n\nexport interface FarmAPIConfigResolverContext {\n  root: string;\n  mode: \"development\" | \"production\";\n  env: ResolvedFarmEnv;\n}\n\nexport type FarmAPIConfigValue =\n  | string\n  | undefined\n  | ((context: FarmAPIConfigResolverContext) => string | undefined | Promise<string | undefined>);\n\nexport interface FarmAPIConfig {\n  /**\n   * Public API root. An origin-only URL is joined with `basePath`; a URL that\n   * already has a path is used as-is. May be resolved from deployment context.\n   */\n  baseURL?: FarmAPIConfigValue;\n  /** Public API path and same-origin server mount used when `baseURL` has no path. @default \"/api\" */\n  basePath?: FarmAPIConfigValue;\n}\n\nexport interface ResolvedFarmAPIConfig {\n  /** Fully resolved public API root, either absolute or root-relative. */\n  baseURL: string;\n  /** Effective pathname of `baseURL`. */\n  basePath: string;\n}\n\ndeclare const __FARM_API_BASE_URL__: string | undefined;\n\nexport async function resolveFarmAPIConfig(\n  config: FarmAPIConfig | undefined,\n  context: FarmAPIConfigResolverContext,\n): Promise<ResolvedFarmAPIConfig> {\n  const configuredBasePath = await resolveConfigValue(config?.basePath, context, \"api.basePath\");\n  const basePath = normalizeFarmAPIBasePath(configuredBasePath ?? DEFAULT_FARM_API_BASE_PATH);\n  const configuredBaseURL = await resolveConfigValue(config?.baseURL, context, \"api.baseURL\");\n\n  return normalizeFarmAPIConfig({ baseURL: configuredBaseURL, basePath });\n}\n\n/** Normalize already-resolved API strings. */\nexport function normalizeFarmAPIConfig(\n  config: { baseURL?: string; basePath?: string } | undefined,\n): ResolvedFarmAPIConfig {\n  const basePath = normalizeFarmAPIBasePath(config?.basePath ?? DEFAULT_FARM_API_BASE_PATH);\n  const baseURL = config?.baseURL?.trim();\n\n  if (!baseURL) {\n    return { baseURL: basePath, basePath };\n  }\n\n  if (baseURL.startsWith(\"//\")) {\n    throw new Error(\n      'Farm api.baseURL must be an absolute URL or a root-relative path such as \"/api\", not a network-path reference.',\n    );\n  }\n\n  if (baseURL.startsWith(\"/\")) {\n    const url = parseRootRelativeBaseURL(baseURL);\n    if (url.pathname !== \"/\") {\n      const effectivePath = normalizeFarmAPIBasePath(url.pathname);\n      return { baseURL: effectivePath, basePath: effectivePath };\n    }\n    return { baseURL: basePath, basePath };\n  }\n\n  let url: URL;\n  try {\n    url = new URL(baseURL);\n  } catch {\n    throw new Error(\n      'Farm api.baseURL must be an absolute URL or a root-relative path such as \"/api\".',\n    );\n  }\n\n  if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n    throw new Error(\"Farm api.baseURL must use http or https.\");\n  }\n  if (url.search || url.hash) {\n    throw new Error(\"Farm api.baseURL cannot contain a query string or hash.\");\n  }\n\n  if (url.pathname !== \"/\") {\n    const effectivePath = normalizeFarmAPIBasePath(url.pathname);\n    return {\n      baseURL: `${url.origin}${effectivePath}`,\n      basePath: effectivePath,\n    };\n  }\n\n  return {\n    baseURL: basePath === \"/\" ? url.origin : `${url.origin}${basePath}`,\n    basePath,\n  };\n}\n\nexport function normalizeFarmAPIBasePath(value: string): string {\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(value)) {\n    throw new Error(\"Farm api.basePath cannot contain backslashes or control characters.\");\n  }\n\n  const path = value.trim();\n  if (!path) {\n    throw new Error(\"Farm api.basePath cannot be empty.\");\n  }\n  if (path.includes(\"?\") || path.includes(\"#\")) {\n    throw new Error(\"Farm api.basePath cannot contain a query string or hash.\");\n  }\n  if (path.startsWith(\"//\")) {\n    throw new Error('Farm api.basePath must be a pathname such as \"/api\", not a URL.');\n  }\n  for (const segment of path.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // A malformed escape remains literal in a URL pathname. It cannot be a\n      // dot segment, so leave the ordinary URL parser to preserve it.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"Farm api.basePath cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"Farm api.basePath cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('Farm api.basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  const normalized = `/${path.replace(/^\\/+|\\/+$/g, \"\")}`;\n  return normalized === \"/\" ? \"/\" : normalized;\n}\n\n/** Read the API root embedded by Farm's Vite build. */\nexport function getFarmAPIBaseURL(): string {\n  if (typeof __FARM_API_BASE_URL__ !== \"undefined\" && __FARM_API_BASE_URL__) {\n    return __FARM_API_BASE_URL__;\n  }\n  return DEFAULT_FARM_API_BASE_PATH;\n}\n\n/** Resolve a canonical Farm route such as `/api/users` against an API root. */\nexport function resolveFarmAPIRequestURL(\n  routePath: string,\n  baseURL = getFarmAPIBaseURL(),\n  fallbackOrigin = getDefaultOrigin(),\n): URL {\n  const base = new URL(baseURL, fallbackOrigin);\n  if (base.pathname === \"/\") {\n    return new URL(routePath, base);\n  }\n\n  const route = new URL(routePath, fallbackOrigin);\n  const suffix = stripCanonicalAPIBasePath(route.pathname);\n  const joinedPath = joinURLPath(base.pathname, suffix);\n  base.pathname = joinedPath;\n  base.search = route.search;\n  base.hash = route.hash;\n  return base;\n}\n\nasync function resolveConfigValue(\n  value: FarmAPIConfigValue,\n  context: FarmAPIConfigResolverContext,\n  name: string,\n): Promise<string | undefined> {\n  const resolved = typeof value === \"function\" ? await value(context) : value;\n  if (resolved === undefined) return undefined;\n  if (typeof resolved !== \"string\") {\n    throw new Error(`Farm ${name} must resolve to a string or undefined.`);\n  }\n  if (!resolved.trim()) {\n    throw new Error(`Farm ${name} cannot be empty.`);\n  }\n  return resolved;\n}\n\nfunction parseRootRelativeBaseURL(value: string): URL {\n  const url = new URL(value, \"http://farm.local\");\n  if (url.search || url.hash) {\n    throw new Error(\"Farm api.baseURL cannot contain a query string or hash.\");\n  }\n  return url;\n}\n\nfunction stripCanonicalAPIBasePath(pathname: string): string {\n  if (pathname === DEFAULT_FARM_API_BASE_PATH) return \"\";\n  if (pathname.startsWith(`${DEFAULT_FARM_API_BASE_PATH}/`)) {\n    return pathname.slice(DEFAULT_FARM_API_BASE_PATH.length + 1);\n  }\n  return pathname.replace(/^\\/+/, \"\");\n}\n\nfunction joinURLPath(basePath: string, suffix: string): string {\n  const normalizedBase = basePath === \"/\" ? \"\" : basePath.replace(/\\/+$/, \"\");\n  const normalizedSuffix = suffix.replace(/^\\/+/, \"\");\n  if (!normalizedSuffix) return normalizedBase || \"/\";\n  return `${normalizedBase}/${normalizedSuffix}`;\n}\n\nfunction getDefaultOrigin(): string {\n  return typeof window !== \"undefined\" ? window.location.origin : \"http://localhost:3000\";\n}\n","import type {\n  build as viteBuild,\n  createServer as createViteServer,\n  loadEnv as viteLoadEnv,\n} from \"vite\";\n\nexport type FarmProductionViteBuilder = \"rollup\" | \"rolldown\";\n\nexport interface FarmProductionViteRuntime {\n  build: typeof viteBuild;\n  createServer: typeof createViteServer;\n  loadEnv: typeof viteLoadEnv;\n  builder: FarmProductionViteBuilder;\n}\n\nexport function canUseRolldownForRouteDiscovery(viteConfig: object | undefined): boolean {\n  return !viteConfig || Object.keys(viteConfig).length === 0;\n}\n\nexport function supportsRolldownVite(nodeVersion = process.versions.node): boolean {\n  const [major = 0, minor = 0] = nodeVersion.split(\".\").map(Number);\n  return major > 22 || (major === 22 && minor >= 12);\n}\n\nfunction requestedProductionViteBuilder(): FarmProductionViteBuilder | undefined {\n  const requested = process.env.FARM_VITE_BUILDER?.trim().toLowerCase();\n  if (!requested) return undefined;\n  if (requested === \"rollup\" || requested === \"rolldown\") return requested;\n  throw new Error('FARM_VITE_BUILDER must be either \"rolldown\" or \"rollup\"');\n}\n\nasync function loadRollupVite(): Promise<FarmProductionViteRuntime> {\n  const runtime = await import(\"vite\");\n  return {\n    build: runtime.build,\n    createServer: runtime.createServer,\n    loadEnv: runtime.loadEnv,\n    builder: \"rollup\",\n  };\n}\n\n/**\n * Prefer Vite's Rolldown-powered production builder on supported Node releases.\n * Vite 5 remains the compatibility path for unsupported runtimes, --no-optional installs,\n * and projects that explicitly request Rollup.\n */\nexport async function loadFarmProductionVite(): Promise<FarmProductionViteRuntime> {\n  const requested = requestedProductionViteBuilder();\n  if (requested === \"rollup\" || !supportsRolldownVite()) {\n    if (requested === \"rolldown\") {\n      throw new Error(\"FARM_VITE_BUILDER=rolldown requires Node 22.12 or newer\");\n    }\n    return loadRollupVite();\n  }\n\n  try {\n    const runtime = (await import(\"vite-rolldown\")) as unknown as typeof import(\"vite\");\n    return {\n      build: runtime.build,\n      createServer: runtime.createServer,\n      loadEnv: runtime.loadEnv,\n      builder: \"rolldown\",\n    };\n  } catch (error) {\n    if (requested === \"rolldown\") {\n      const detail = error instanceof Error ? `: ${error.message}` : \"\";\n      throw new Error(\n        `FARM_VITE_BUILDER=rolldown was requested, but the optional Vite Rolldown runtime could not be loaded${detail}`,\n      );\n    }\n    return loadRollupVite();\n  }\n}\n"],"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;AAAA;AAoHA,SAAS,sBAA+B;AACtC,aAAO,gCAAc;AAAA,IACnB,YAAQ,cAAAA,SAAa;AAAA,EACvB,CAAC;AACH;AAIA,SAAS,oBAAyC;AAChD,SAAQ,WAAmE,kBAAkB;AAC/F;AAEA,SAAS,mBAAmB,SAA2B;AACrD,EAAC,WAAmE,kBAAkB,IAAI;AAC1F,SAAO;AACT;AAEA,SAAS,yBAAkC;AACzC,QAAM,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AM,YAAY,QAAQ,IAAI,mBAAmB,KAAK,EAAE,YAAY;AACpE,MAAI,CAAC,UAAW,QAAO;AACvB,MAAI,cAAc,YAAY,cAAc,WAAY,QAAO;AAC/D,QAAM,IAAI,MAAM,yDAAyD;AAC3E;AALS;AAOT,eAAe,iBAAqD;AAClE,QAAM,UAAU,MAAM,OAAO,MAAM;AACnC,SAAO;AAAA,IACL,OAAO,QAAQ;AAAA,IACf,cAAc,QAAQ;AAAA,IACtB,SAAS,QAAQ;AAAA,IACjB,SAAS;AAAA,EACX;AACF;AARe;AAef,eAAsB,yBAA6D;AACjF,QAAM,YAAY,+BAA+B;AACjD,MAAI,cAAc,YAAY,CAAC,qBAAqB,GAAG;AACrD,QAAI,cAAc,YAAY;AAC5B,YAAM,IAAI,MAAM,yDAAyD;AAAA,IAC3E;AACA,WAAO,eAAe;AAAA,EACxB;AAEA,MAAI;AACF,UAAM,UAAW,MAAM,OAAO,eAAe;AAC7C,WAAO;AAAA,MACL,OAAO,QAAQ;AAAA,MACf,cAAc,QAAQ;AAAA,MACtB,SAAS,QAAQ;AAAA,MACjB,SAAS;AAAA,IACX;AAAA,EACF,SAAS,OAAO;AACd,QAAI,cAAc,YAAY;AAC5B,YAAM,SAAS,iBAAiB,QAAQ,KAAK,MAAM,OAAO,KAAK;AAC/D,YAAM,IAAI;AAAA,QACR,uGAAuG,MAAM;AAAA,MAC/G;AAAA,IACF;AACA,WAAO,eAAe;AAAA,EACxB;AACF;AA1BsB;","names":["memoryDriver","module","resolveDriver","base","globalState","path","path","globalState","env","path","response","resolveStorageRuntimeClient","createIntegrationOrm","isAbsolutePath","normalizePath","path","env","env","globalState","import_node_path","path","path","path","path","import_node_path","path","import_node_module","import_node_path","import_node_url","path","normalizeCookiePath","import_node_module","import_node_path","import_node_url","import_promises","import_node_module","import_node_path","import_node_url","path","path","url","path","env","existsSync","path","isRecord","pathToFileURL","api"]}