/** * Capture console output into a ring buffer and fan out to subscribers (editor). */ const MAX_LINES = 2500; /** @type {Array<{ t: number, level: string, text: string }>} */ const lines = []; /** @type {Set<(entry: { t: number, level: string, text: string }) => void>} */ const listeners = new Set(); let hooked = false; function formatArgs (args) { return args.map((arg) => { if (typeof arg === "string") { return arg; } try { return JSON.stringify(arg); } catch { return String(arg); } }).join(" "); } function push (level, args) { const entry = { t: Date.now(), level, text: formatArgs(args) }; lines.push(entry); if (lines.length > MAX_LINES) { lines.splice(0, lines.length - MAX_LINES); } for (const listener of listeners) { try { listener(entry); } catch { /* ignore subscriber errors */ } } } export function hookConsoleCapture () { if (hooked) { return; } hooked = true; for (const level of ["log", "info", "warn", "error", "debug"]) { const original = console[level]?.bind(console); if (!original) { continue; } console[level] = (...args) => { push(level === "log" ? "info" : level, args); original(...args); }; } } export function getConsoleSnapshot (limit = 500) { const n = Math.max(1, Math.min(MAX_LINES, limit | 0 || 500)); return lines.slice(-n); } export function subscribeConsole (listener) { listeners.add(listener); return () => listeners.delete(listener); }