opencode-ccgo-provider/scripts/opencode-config.mjs

30 lines
1.3 KiB
JavaScript

// Shared by quota.mjs and sync-models.mjs: locate the opencode config and the CommandCode
// API key the same way the provider does.
import { readFileSync } from "node:fs";
import { PROVIDER_ID } from "../dist/constants.js";
/** Parse an opencode.json; a missing file is `{ text: "", data: {}, exists: false }`. */
export function readConfig(path) {
try {
const text = readFileSync(path, "utf8");
return { text, data: JSON.parse(text), exists: true };
} catch (error) {
// A fresh install has no opencode.json yet; treat it as empty. Bad JSON or unreadable
// files still throw.
if (error.code === "ENOENT") return { text: "", data: {}, exists: false };
throw error;
}
}
/** COMMANDCODE_API_KEY, then provider options apiKey, then a configured Authorization header. */
export function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
const options = config?.provider?.[PROVIDER_ID]?.options ?? {};
const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization;
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
return undefined;
}