(value: unknown)
| 41 | * Safely stringifies terminal data without throwing on circular or non-JSON-safe values. |
| 42 | */ |
| 43 | export function safeConsoleStringify(value: unknown): string { |
| 44 | const seen = new WeakSet<object>() |
| 45 | |
| 46 | try { |
| 47 | return ( |
| 48 | JSON.stringify( |
| 49 | value, |
| 50 | (_key, currentValue) => { |
| 51 | if (typeof currentValue === 'bigint') { |
| 52 | return `${currentValue.toString()}n` |
| 53 | } |
| 54 | |
| 55 | if (currentValue instanceof Error) { |
| 56 | return { |
| 57 | name: currentValue.name, |
| 58 | message: currentValue.message, |
| 59 | stack: currentValue.stack, |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | if (typeof currentValue === 'function') { |
| 64 | return `[Function ${currentValue.name || 'anonymous'}]` |
| 65 | } |
| 66 | |
| 67 | if (typeof currentValue === 'symbol') { |
| 68 | return currentValue.toString() |
| 69 | } |
| 70 | |
| 71 | if (typeof currentValue === 'object' && currentValue !== null) { |
| 72 | if (seen.has(currentValue)) { |
| 73 | return '[Circular]' |
| 74 | } |
| 75 | |
| 76 | seen.add(currentValue) |
| 77 | } |
| 78 | |
| 79 | return currentValue |
| 80 | }, |
| 81 | 2 |
| 82 | ) ?? '' |
| 83 | ) |
| 84 | } catch { |
| 85 | try { |
| 86 | return String(value) |
| 87 | } catch { |
| 88 | return '[Unserializable value]' |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | /** |
| 94 | * Produces a terminal-safe representation of any value. |
no test coverage detected