auth-runtime/dist/env.js

57 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
const GLOBAL_ENV_PATH = path.join(os.homedir(), '.openclaw', '.env');
/** Keys that were loaded from .env (not pre-existing in process.env) */
const loadedKeys = new Set();
let loaded = false;
/**
* Load ~/.openclaw/.env into process.env (once, won't overwrite explicitly set env vars).
*/
export function loadGlobalEnv() {
if (loaded)
return;
loaded = true;
applyEnvFile();
}
/**
* Force re-read ~/.openclaw/.env. Overwrites keys that were originally loaded
* from .env, but still won't touch keys set externally (e.g. shell export).
*/
export function reloadGlobalEnv() {
// Clear values we previously loaded so applyEnvFile can overwrite them
for (const key of loadedKeys) {
delete process.env[key];
}
loadedKeys.clear();
applyEnvFile();
}
function applyEnvFile() {
let content;
try {
content = fs.readFileSync(GLOBAL_ENV_PATH, 'utf-8');
}
catch {
return; // file doesn't exist — that's fine
}
for (const line of content.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#'))
continue;
const eqIdx = trimmed.indexOf('=');
if (eqIdx < 1)
continue;
const key = trimmed.slice(0, eqIdx).trim();
let value = trimmed.slice(eqIdx + 1).trim();
// strip surrounding quotes
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
// don't overwrite explicitly set env vars
if (process.env[key] === undefined) {
process.env[key] = value;
loadedKeys.add(key);
}
}
}
//# sourceMappingURL=env.js.map