/** * Copyright (c) 2026, Salesforce, Inc., * All rights reserved. * For full license text, see the LICENSE.txt file */ /** * Capture text written to process.stdout (or via console.log) while `fn` runs. * Restores the original write function and console.log in a finally block, * even if `fn` throws. * * Note: Vitest intercepts console.log before process.stdout.write, so both * must be patched to capture all output reliably in a Vitest environment. */ export async function captureStdout(fn: () => unknown | Promise): Promise { const chunks: string[] = []; const originalWrite = process.stdout.write.bind(process.stdout); const originalLog = console.log; process.stdout.write = ((c: unknown) => { chunks.push(typeof c === "string" ? c : String(c)); return true; }) as typeof process.stdout.write; console.log = (...args: unknown[]) => { chunks.push(args.map((a) => (typeof a === "string" ? a : String(a))).join(" ") + "\n"); }; try { await fn(); } finally { process.stdout.write = originalWrite; console.log = originalLog; } return chunks.join(""); }