feat: add config schema and loader with env var expansion
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { parse } from 'yaml';
|
||||
import { configSchema, type Config } from './schema.js';
|
||||
|
||||
function expandEnvVars(value: string): string {
|
||||
return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
|
||||
const envValue = process.env[envVar];
|
||||
if (envValue === undefined) {
|
||||
throw new Error(`Environment variable ${envVar} is not set`);
|
||||
}
|
||||
return envValue;
|
||||
});
|
||||
}
|
||||
|
||||
function expandEnvVarsInObject(obj: unknown): unknown {
|
||||
if (typeof obj === 'string') {
|
||||
return expandEnvVars(obj);
|
||||
}
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map(expandEnvVarsInObject);
|
||||
}
|
||||
if (obj !== null && typeof obj === 'object') {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
result[key] = expandEnvVarsInObject(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
export function loadConfig(configPath: string): Config {
|
||||
const rawContent = readFileSync(configPath, 'utf-8');
|
||||
const rawConfig = parse(rawContent);
|
||||
const expandedConfig = expandEnvVarsInObject(rawConfig);
|
||||
return configSchema.parse(expandedConfig);
|
||||
}
|
||||
Reference in New Issue
Block a user