Files
flynn/src/config/loader.ts
T
2026-02-02 20:54:19 -08:00

38 lines
1.1 KiB
TypeScript

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);
}