/** * Universal config diff tool. * Compare two config files in any supported format (JSON, YAML, TOML, INI). * Shows additions, removals, and changes with path information. */ import { parseJsonc } from "./json-config.js"; import { parseYaml } from "./yaml-config.js"; import { parseToml } from "./toml-parser.js"; import { parseIni, iniToJson } from "./ini-parser.js"; export type ConfigFormat = "json" | "yaml" | "toml" | "ini" | "auto"; export interface DiffEntry { path: string; type: "added" | "removed" | "changed"; oldValue?: unknown; newValue?: unknown; } export interface DiffResult { totalChanges: number; additions: number; removals: number; modifications: number; entries: DiffEntry[]; } /** Detect format from content heuristics. */ function detectFormat(content: string): ConfigFormat { const trimmed = content.trim(); // JSON starts with { or [ if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json"; // TOML has [section] headers and key = "value" patterns if (/^\[[\w.]+\]\s*$/m.test(trimmed) && /^\w[\w-]*\s*=\s*/m.test(trimmed)) { // Distinguish TOML from INI: TOML uses = only, INI may use : too // TOML values are typed; check for TOML-specific patterns if (/=\s*\[/m.test(trimmed) || /=\s*"""/m.test(trimmed) || /=\s*true|=\s*false/m.test(trimmed)) { return "toml"; } } // YAML typically has key: value without [sections] if (/^[\w-]+\s*:/m.test(trimmed) && !/^\[/m.test(trimmed)) return "yaml"; // INI has [sections] with key=value or key:value if (/^\[[\w\s.]+\]/m.test(trimmed)) return "ini"; // Default to JSON return "json"; } /** Parse config content using the specified or auto-detected format. */ export function parseConfig(content: string, format: ConfigFormat = "auto"): unknown { const fmt = format === "auto" ? detectFormat(content) : format; switch (fmt) { case "json": return parseJsonc(content); case "yaml": return parseYaml(content); case "toml": return parseToml(content); case "ini": return iniToJson(parseIni(content)); default: throw new Error(`Unsupported format: ${fmt}`); } } /** Check if a value is a plain object. */ function isPlainObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } /** Recursively compute differences between two structures. */ function computeDiffs(a: unknown, b: unknown, prefix: string = ""): DiffEntry[] { const entries: DiffEntry[] = []; if (!isPlainObject(a) || !isPlainObject(b)) { if (JSON.stringify(a) !== JSON.stringify(b)) { entries.push({ path: prefix || "(root)", type: "changed", oldValue: a, newValue: b }); } return entries; } const allKeys = new Set([...Object.keys(a), ...Object.keys(b)]); for (const key of allKeys) { const fullPath = prefix ? `${prefix}.${key}` : key; const inA = key in a; const inB = key in b; if (inA && !inB) { entries.push({ path: fullPath, type: "removed", oldValue: a[key] }); } else if (!inA && inB) { entries.push({ path: fullPath, type: "added", newValue: b[key] }); } else if (isPlainObject(a[key]) && isPlainObject(b[key])) { entries.push(...computeDiffs(a[key], b[key], fullPath)); } else if (Array.isArray(a[key]) && Array.isArray(b[key])) { if (JSON.stringify(a[key]) !== JSON.stringify(b[key])) { entries.push({ path: fullPath, type: "changed", oldValue: a[key], newValue: b[key] }); } } else if (JSON.stringify(a[key]) !== JSON.stringify(b[key])) { entries.push({ path: fullPath, type: "changed", oldValue: a[key], newValue: b[key] }); } } return entries; } /** Compare two config file contents and return structured diff. */ export function diffConfigs( contentA: string, contentB: string, formatA: ConfigFormat = "auto", formatB: ConfigFormat = "auto" ): DiffResult { const dataA = parseConfig(contentA, formatA); const dataB = parseConfig(contentB, formatB); const entries = computeDiffs(dataA, dataB); return { totalChanges: entries.length, additions: entries.filter((e) => e.type === "added").length, removals: entries.filter((e) => e.type === "removed").length, modifications: entries.filter((e) => e.type === "changed").length, entries, }; } /** Format a diff result as a human-readable string. */ export function formatDiff(result: DiffResult): string { if (result.totalChanges === 0) { return "No differences found."; } const lines: string[] = [ `Found ${result.totalChanges} difference(s): ${result.additions} added, ${result.removals} removed, ${result.modifications} changed.`, "", ]; for (const entry of result.entries) { switch (entry.type) { case "added": lines.push(`+ ${entry.path}: ${JSON.stringify(entry.newValue)}`); break; case "removed": lines.push(`- ${entry.path}: ${JSON.stringify(entry.oldValue)}`); break; case "changed": lines.push(`~ ${entry.path}:`); lines.push(` old: ${JSON.stringify(entry.oldValue)}`); lines.push(` new: ${JSON.stringify(entry.newValue)}`); break; } } return lines.join("\n"); }