sandlot/src/env.ts
Chris Wanstrath 1d55cf427e no oauth
2026-02-25 15:52:22 -08:00

20 lines
698 B
TypeScript

import { homedir } from "os"
import { join } from "path"
import { die } from "./fmt.ts"
/** Read the ANTHROPIC_API_KEY from ~/.env. Returns undefined if not found. */
export async function getApiKey(): Promise<string | undefined> {
const envFile = Bun.file(join(homedir(), ".env"))
if (!(await envFile.exists())) return undefined
const envContent = await envFile.text()
return envContent.match(/^(?:export\s+)?ANTHROPIC_API_KEY=["']?([^"'\s]+)["']?/m)?.[1]
}
/** Read the ANTHROPIC_API_KEY from ~/.env, dying if not found. */
export async function requireApiKey(): Promise<string> {
const key = await getApiKey()
if (!key) die("ANTHROPIC_API_KEY not found in ~/.env")
return key
}