()
| 343 | |
| 344 | /** Wire up window error + console.error/warn capture into the trace buffer. */ |
| 345 | export function installClientErrorCapture(): void { |
| 346 | if (clientCaptureInstalled || !isTraceEnabled()) return; |
| 347 | clientCaptureInstalled = true; |
| 348 | |
| 349 | try { |
| 350 | if (typeof window !== 'undefined') { |
| 351 | window.addEventListener('error', (e: ErrorEvent) => { |
| 352 | traceClientLog('error', e.message || 'window error', { |
| 353 | source: e.filename, |
| 354 | line: e.lineno, |
| 355 | col: e.colno, |
| 356 | stack: e.error instanceof Error ? e.error.stack : undefined, |
| 357 | }); |
| 358 | }); |
| 359 | window.addEventListener('unhandledrejection', (e: PromiseRejectionEvent) => { |
| 360 | const reason = e.reason; |
| 361 | traceClientLog('error', 'unhandled promise rejection', { |
| 362 | reason: reason instanceof Error ? `${reason.name}: ${reason.message}` : reason, |
| 363 | stack: reason instanceof Error ? reason.stack : undefined, |
| 364 | }); |
| 365 | }); |
| 366 | } |
| 367 | } catch { |
| 368 | // window unavailable |
| 369 | } |
| 370 | |
| 371 | for (const level of ['error', 'warn', 'log', 'info', 'debug'] as const) { |
| 372 | const original = console[level]; |
| 373 | if (typeof original !== 'function') continue; |
| 374 | console[level] = (...args: unknown[]): void => { |
| 375 | try { |
| 376 | traceClientLog(level, args.map(stringifyArg).join(' '), args.length > 1 ? args : args[0]); |
| 377 | } catch { |
| 378 | // never let tracing break logging |
| 379 | } |
| 380 | original.apply(console, args); |
| 381 | }; |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | function stringifyArg(a: unknown): string { |
| 386 | if (typeof a === 'string') return a; |
no test coverage detected