Files
OmniRoute/src/lib/db/omp.ts
Chirag 66b85466ce fix: resolve Windows Electron build failures for missing native modules (#8959)
Validated in local merge-train (devbox-vm-06-dev002) @ combined-tip (FAST gates green: static + changed tests + vitest — only pre-existing audit.test.ts flake). Evidence: /home/diegosouzapw/dev/proxys/OmniRoute/.claude/worktrees/merge-train-20260805-213228-suite.log
2026-08-05 21:42:02 -03:00

78 lines
2.5 KiB
TypeScript

import os from "os";
import path from "path";
import { createRequire } from "node:module";
const _require = createRequire(import.meta.url);
function getDatabaseClass() {
try {
if (process.versions.bun) {
return _require("bun:sqlite").Database;
}
return _require("better-sqlite3");
} catch {
return null;
}
}
const Database = process.versions.bun
? (_require("bun:sqlite").Database as typeof import("better-sqlite3"))
: (_require("better-sqlite3") as typeof import("better-sqlite3"));
function databaseOptions(readonly = false) {
return readonly ? { readonly: true } : { readwrite: true, create: true };
}
const getOmpDir = () => path.join(os.homedir(), ".omp", "agent");
const getOmpDbPath = () => path.join(getOmpDir(), "agent.db");
export function getOmpCredentials(providerId: string) {
const Database = getDatabaseClass();
if (!Database) return { hasOmniRoute: false, baseUrl: null, apiKey: null };
const dbPath = getOmpDbPath();
try {
const db = new Database(dbPath, databaseOptions(true));
const row = db
.prepare(
"SELECT data FROM auth_credentials WHERE provider = ? AND credential_type = 'api_key'"
)
.get(providerId) as { data: string } | undefined;
db.close();
if (row?.data) {
const parsed = JSON.parse(row.data);
return { hasOmniRoute: true, baseUrl: parsed.baseUrl || null, apiKey: parsed.apiKey || null };
}
return { hasOmniRoute: false, baseUrl: null, apiKey: null };
} catch {
return { hasOmniRoute: false, baseUrl: null, apiKey: null };
}
}
export function saveOmpCredentials(providerId: string, apiKey: string, baseUrl: string) {
const Database = getDatabaseClass();
if (!Database) return;
const dbPath = getOmpDbPath();
const db = new Database(dbPath, databaseOptions());
db.prepare("DELETE FROM auth_credentials WHERE provider = ?").run(providerId);
db.prepare(
"INSERT INTO auth_credentials (provider, credential_type, data, disabled_cause, identity_key, created_at, updated_at) VALUES (?, ?, ?, NULL, NULL, ?, ?)"
).run(
providerId,
"api_key",
JSON.stringify({ apiKey, baseUrl }),
Math.floor(Date.now() / 1000),
Math.floor(Date.now() / 1000)
);
db.close();
}
export function deleteOmpCredentials(providerId: string) {
const Database = getDatabaseClass();
if (!Database) return;
const dbPath = getOmpDbPath();
const db = new Database(dbPath, databaseOptions());
db.prepare("DELETE FROM auth_credentials WHERE provider = ?").run(providerId);
db.close();
}