safevibe
Version:
Safevibe CLI - Simple personal secret vault for AI developers and amateur vibe coders
110 lines (109 loc) • 3.04 kB
JavaScript
import { readFile, writeFile, mkdir, access } from "node:fs/promises";
import { join } from "node:path";
import { homedir } from "node:os";
import { constants } from "node:fs";
/**
* Default configuration
*/
const defaultConfig = {
backendUrl: "https://safevibe-backend.vercel.app",
created: new Date().toISOString(),
updated: new Date().toISOString(),
};
/**
* Configuration file paths
*/
export const CONFIG_DIR = join(homedir(), ".safevibe");
export const CONFIG_FILE = join(CONFIG_DIR, "config.json");
export const KEYS_FILE = join(CONFIG_DIR, "keys.json");
/**
* Check if Safevibe is initialized (config exists)
*/
export async function isInitialized() {
try {
await access(CONFIG_FILE, constants.F_OK);
return true;
}
catch {
return false;
}
}
/**
* Load configuration from disk
*/
export async function loadConfig() {
try {
const configData = await readFile(CONFIG_FILE, "utf-8");
const config = JSON.parse(configData);
// Merge with defaults for any missing fields
return { ...defaultConfig, ...config };
}
catch (error) {
if (error.code === "ENOENT") {
throw new Error("Safevibe not initialized. Run 'safevibe init' to get started.");
}
throw new Error(`Failed to load config: ${error.message}`);
}
}
/**
* Save configuration to disk
*/
export async function saveConfig(config) {
try {
// Ensure config directory exists
await mkdir(CONFIG_DIR, { recursive: true });
// Update timestamp
config.updated = new Date().toISOString();
// Save configuration
await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
}
catch (error) {
throw new Error(`Failed to save config: ${error.message}`);
}
}
/**
* Initialize configuration with defaults
*/
export async function initConfig(options) {
// Check if already initialized
if (!options.force && (await isInitialized())) {
throw new Error("Safevibe already initialized. Use --force to overwrite existing configuration.");
}
// Create initial configuration
const config = {
...defaultConfig,
backendUrl: options.backendUrl || defaultConfig.backendUrl,
sessionToken: options.sessionToken,
userId: options.userId,
};
// Save configuration
await saveConfig(config);
return config;
}
/**
* Update configuration with new values
*/
export async function updateConfig(updates) {
const currentConfig = await loadConfig();
const newConfig = { ...currentConfig, ...updates };
await saveConfig(newConfig);
return newConfig;
}
/**
* Get a specific configuration value
*/
export async function getConfigValue(key) {
try {
const config = await loadConfig();
return config[key];
}
catch {
return undefined;
}
}
/**
* Reset configuration to defaults
*/
export async function resetConfig() {
await saveConfig(defaultConfig);
}