UNPKG

@wavequery/conductor

Version:
107 lines 3.11 kB
import { z } from "zod"; export class ConfigManager { constructor(options = {}) { this.options = { schema: z.record(z.any()), defaultValues: {}, onUpdate: () => { }, persist: false, storage: typeof localStorage !== "undefined" ? localStorage : null, ...options, }; this.config = this.loadConfig(); } static getInstance(options) { if (!ConfigManager.instance) { ConfigManager.instance = new ConfigManager(options); } return ConfigManager.instance; } get(key) { return this.config[key]; } set(key, value) { const updates = { [key]: value }; this.validateUpdates(updates); this.config[key] = value; this.handleConfigUpdate(); } update(updates) { this.validateUpdates(updates); this.config = { ...this.config, ...updates, }; this.handleConfigUpdate(); } reset() { this.config = { ...this.options.defaultValues }; this.handleConfigUpdate(); } validateUpdates(updates) { try { const newConfig = { ...this.config, ...updates }; this.options.schema.parse(newConfig); } catch (error) { if (error instanceof z.ZodError) { throw new Error(`Invalid config update: ${error.errors.map((e) => e.message).join(", ")}`); } throw error; } } handleConfigUpdate() { if (this.options.persist) { this.saveConfig(); } this.options.onUpdate(this.config); } get storageKey() { return "conductor_config"; } loadConfig() { if (!this.options.persist || !this.options.storage) { return { ...this.options.defaultValues }; } try { const stored = this.options.storage.getItem(this.storageKey); if (!stored) { return { ...this.options.defaultValues }; } const parsed = JSON.parse(stored); const validated = this.options.schema.parse(parsed); return { ...this.options.defaultValues, ...validated, }; } catch (error) { return { ...this.options.defaultValues }; } } saveConfig() { if (!this.options.storage) return; try { this.options.storage.setItem(this.storageKey, JSON.stringify(this.config)); } catch (error) { console.error("Failed to save config:", error); } } getSnapshot() { return { ...this.config }; } watchKey(key, callback) { const handler = (config) => { callback(config[key]); }; this.options.onUpdate = handler; return () => { if (this.options.onUpdate === handler) { this.options.onUpdate = () => { }; } }; } } //# sourceMappingURL=config-manager.js.map