UNPKG

counterfact

Version:

Generate a TypeScript-based mock server from an OpenAPI spec in seconds — with stateful routes, hot reload, and REPL support.

45 lines (44 loc) 1.52 kB
import { load as loadYaml } from "js-yaml"; import { readFile } from "./read-file.js"; function kebabToCamel(str) { return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()); } function normalizeKeys(obj) { return Object.fromEntries(Object.entries(obj).map(([key, value]) => [kebabToCamel(key), value])); } /** * Loads and parses a counterfact YAML config file. * * @param configPath - Absolute or relative path to the config file. * @param required - When true, throws if the file does not exist. * When false (default), returns an empty object for missing files. * @returns A plain object of config keys (camelCase) to values. */ export async function loadConfigFile(configPath, required = false) { let content; try { content = await readFile(configPath); } catch (error) { if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") { if (required) { throw new Error(`Config file not found: ${configPath}`, { cause: error, }); } return {}; } throw error; } const parsed = loadYaml(content); if (parsed === null || parsed === undefined) { return {}; } if (typeof parsed !== "object" || Array.isArray(parsed)) { throw new Error(`Config file must be a YAML object (mapping): ${configPath}`); } return normalizeKeys(parsed); }