import { z } from "zod"; // Shared by the web app and the worker. Never import this from a client component: // it contains HF_TOKEN. Web code should go through "@/lib/server-env", which is guarded // by "server-only". const emptyToUndefined = (v: unknown) => (v === "" ? undefined : v); const coreSchema = z.object({ HF_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()), MODELS_DIR: z.preprocess(emptyToUndefined, z.string().default("/models")), DATABASE_URL: z.preprocess(emptyToUndefined, z.string().default("file:/data/app.db")), MAX_CONCURRENT_DOWNLOADS: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).default(1)), UPDATE_CHECK_INTERVAL_HOURS: z.preprocess(emptyToUndefined, z.coerce.number().min(0).default(12)), }); const authSchema = z.object({ OIDC_ISSUER: z.url(), OIDC_CLIENT_ID: z.string().min(1), OIDC_CLIENT_SECRET: z.string().min(1), OIDC_ALLOWED_GROUPS: z.preprocess( (v) => typeof v === "string" ? v .split(",") .map((g) => g.trim()) .filter(Boolean) : [], z.array(z.string()), ), }); export type CoreEnv = z.infer; export type AuthEnv = z.infer; let core: CoreEnv | undefined; let auth: AuthEnv | undefined; function parse(schema: T, name: string): z.infer { const result = schema.safeParse(process.env); if (!result.success) { const issues = result.error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n"); throw new Error(`Invalid ${name} environment:\n${issues}`); } return result.data; } /** Config needed by both web and worker. Parsed lazily so `next build` works without env. */ export function coreEnv(): CoreEnv { return (core ??= parse(coreSchema, "core")); } /** OIDC config, only needed by the web app. */ export function authEnv(): AuthEnv { return (auth ??= parse(authSchema, "auth")); }