import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import dotenv from "dotenv"; import chokidar, { type FSWatcher } from "chokidar"; import { parse as parseYaml } from "yaml"; import { configSchema, type Config } from "./schema"; import { interpolateEnv } from "./interpolate"; import { createLogger } from "@/lib/logger"; const log = createLogger("config"); const CONFIG_DIR = path.join(process.cwd(), "config"); const CONFIG_PATH = path.join(CONFIG_DIR, "config.yml"); const ENV_PATH = path.join(CONFIG_DIR, ".env"); function widgetCount(config: Config): number { return config.groups.reduce((sum, group) => sum + group.widgets.length, 0); } export class ConfigError extends Error {} function loadEnv(): Record { if (!existsSync(ENV_PATH)) return { ...process.env }; const parsed = dotenv.parse(readFileSync(ENV_PATH)); return { ...process.env, ...parsed }; } export function readConfig(): Config { if (!existsSync(CONFIG_PATH)) { throw new ConfigError(`Config file not found at ${CONFIG_PATH}`); } const raw = readFileSync(CONFIG_PATH, "utf-8"); const env = loadEnv(); let interpolated: string; try { interpolated = interpolateEnv(raw, env); } catch (err) { throw new ConfigError((err as Error).message); } let parsedYaml: unknown; try { parsedYaml = parseYaml(interpolated); } catch (err) { throw new ConfigError(`Failed to parse config.yml: ${(err as Error).message}`); } const result = configSchema.safeParse(parsedYaml); if (!result.success) { const issues = result.error.issues .map((issue) => ` - ${issue.path.join(".") || "(root)"}: ${issue.message}`) .join("\n"); throw new ConfigError(`config.yml failed validation:\n${issues}`); } return result.data; } type ConfigListener = (config: Config) => void; type ConfigErrorListener = (error: ConfigError) => void; class ConfigStore { private current: Config | null = null; private watcher: FSWatcher | null = null; private readonly listeners = new Set(); private readonly errorListeners = new Set(); load(): Config { this.current = readConfig(); log.info("config loaded", { groups: this.current.groups.length, widgets: widgetCount(this.current) }); return this.current; } get(): Config { return this.current ?? this.load(); } onUpdate(listener: ConfigListener): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } onError(listener: ConfigErrorListener): () => void { this.errorListeners.add(listener); return () => this.errorListeners.delete(listener); } watch(): void { if (this.watcher) return; this.watcher = chokidar.watch([CONFIG_PATH, ENV_PATH], { awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 }, ignoreInitial: true, }); this.watcher.on("all", (event) => { log.debug("watched file changed", { event }); this.reload(); }); log.info("watching config files", { paths: [CONFIG_PATH, ENV_PATH] }); } stop(): void { this.watcher?.close(); this.watcher = null; } private reload(): void { try { const next = readConfig(); this.current = next; log.info("config reloaded", { groups: next.groups.length, widgets: widgetCount(next) }); for (const listener of this.listeners) listener(next); } catch (err) { const configError = err instanceof ConfigError ? err : new ConfigError((err as Error).message); log.error("config reload failed", { error: configError.message }); for (const listener of this.errorListeners) listener(configError); } } } // Next.js bundles app/** through its own compiler pass, giving it a module // registry separate from server.ts (loaded directly via tsx). A plain module // singleton would end up duplicated - one instance watched by server.ts, // another frozen instance used by SSR. Both still share the same Node // process/heap, so keying off globalThis gives every module graph the same // instance. declare global { var __pulsenodeConfigStore: ConfigStore | undefined; } export const configStore = globalThis.__pulsenodeConfigStore ?? new ConfigStore(); globalThis.__pulsenodeConfigStore = configStore;