diff --git a/.changeset/stamp-debug-ids-on-synthetic-frames.md b/.changeset/stamp-debug-ids-on-synthetic-frames.md new file mode 100644 index 00000000..50e4280a --- /dev/null +++ b/.changeset/stamp-debug-ids-on-synthetic-frames.md @@ -0,0 +1,24 @@ +--- +'@bugsee/core': patch +'@bugsee/browser': patch +--- + +Fix: errors that are not `Error` objects shipped minified stack frames that could never be symbolicated. + +`logException(false)`, `Promise.reject({ ... })`, an Angular `HttpErrorResponse` handed to `ErrorHandler.handleError`: a thrown +value with no stack of its own is reported with the CALLER's frames. Those frames were stamped with their source-map `debug_id` +only when a frame enricher happened to hand back a different array, so in the common case (no enricher, or one that returns the +frames it was given) they went out without one. The worker symbolicates per frame by `debug_id`, so it left them minified, and +because a report with no debug-ids is indistinguishable from one with nothing to resolve it came back `ready`, never +`missing_sym`: nothing flagged it, even with the build's source maps uploaded. + +The caller-site frames are now stamped before the enricher sees them, exactly as a real `Error`'s frames are, and again if the +enricher replaces them. + +Also: an `error` event with no thrown value (`event.error == null`, e.g. a script error on another origin) built its frame by +hand as `{ trace, user }`, with no `debug_id` and no structured position. It now goes through the same frame conversion as every +other frame, and its description carries the `debugId=` suffix a real stack's does. + +Adds debug-id regression coverage for every capture path that produces frames: node uncaught exception and unhandled rejection, +the app-hang stack (ESM `file://` and CommonJS registrations), the edge runtime, cause chains, and the end-to-end +`client.logException` path for non-Errors. diff --git a/packages/browser/src/detection-providers.test.ts b/packages/browser/src/detection-providers.test.ts index 4290c524..4b5f9329 100644 --- a/packages/browser/src/detection-providers.test.ts +++ b/packages/browser/src/detection-providers.test.ts @@ -125,6 +125,78 @@ describe('createWindowErrorProvider', () => { }); }); + it('gives the frame of an error event WITHOUT a thrown value its debug_id and structured position', () => { + // The worker symbolicates per frame by `debug_id`, from the frame's `trace` (data is the fallback). This frame + // used to be hand-built as `{ trace, user }`: no `debug_id`, so a minified `filename:lineno:colno` shipped as is. + const g = globalThis as { _bugseeDebugIds?: Record }; + const prev = g._bugseeDebugIds; + g._bugseeDebugIds = { 'Error\n at reg (https://app.test/page.js:1:1)': 'dbg-event' }; + try { + const w = fakeWindow(); + const requests = started(createWindowErrorProvider(w.win)); + w.emit('error', { + error: null, + message: 'Uncaught ReferenceError: x is not defined', + filename: 'https://app.test/page.js', + lineno: 12, + colno: 5, + }); + const crash = requests[0]?.report.crash as CrashJson; + expect(crash.exception.frames).toEqual([ + { + trace: 'at (https://app.test/page.js:12:5)', + user: true, + debug_id: 'dbg-event', + data: { source: 'https://app.test/page.js', line: 12, column: 5 }, + }, + ]); + expect(crash.exception.name).toBe('Error'); + expect(crash.exception.reason).toBe('Uncaught ReferenceError: x is not defined'); + expect(requests[0]?.report.description).toContain('debugId=dbg-event'); + } finally { + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }); + + it('ships no reason for an error event with a filename but an EMPTY message (not a JSON dump of the carrier)', () => { + const w = fakeWindow(); + const requests = started(createWindowErrorProvider(w.win)); + w.emit('error', { + error: null, + message: '', + filename: 'https://app.test/page.js', + lineno: 1, + colno: 2, + }); + const crash = requests[0]?.report.crash as CrashJson; + expect(crash.exception.name).toBe('Error'); + expect('reason' in crash.exception).toBe(false); + }); + + it('ships no debug_id for an error event from a file no bundle registered', () => { + const g = globalThis as { _bugseeDebugIds?: Record }; + const prev = g._bugseeDebugIds; + g._bugseeDebugIds = { 'Error\n at reg (https://app.test/other.js:1:1)': 'dbg-other' }; + try { + const w = fakeWindow(); + const requests = started(createWindowErrorProvider(w.win)); + w.emit('error', { + error: undefined, + message: 'x', + filename: 'https://app.test/page.js', + lineno: 1, + colno: 2, + }); + const frame = (requests[0]?.report.crash as CrashJson).exception.frames[0]; + expect(frame?.debug_id).toBeUndefined(); + expect(requests[0]?.report.description).not.toContain('debugId='); + } finally { + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }); + it('falls back to message when event.error is undefined (not just null)', () => { const w = fakeWindow(); const requests = started(createWindowErrorProvider(w.win)); diff --git a/packages/browser/src/detection-providers.ts b/packages/browser/src/detection-providers.ts index e464b6e4..0301626d 100644 --- a/packages/browser/src/detection-providers.ts +++ b/packages/browser/src/detection-providers.ts @@ -1,5 +1,5 @@ import type { AsyncOriginReporting } from '@bugsee/capture'; -import type { CrashJson, DetectionProvider } from '@bugsee/core'; +import type { CrashJson, DetectionProvider, StackFrame } from '@bugsee/core'; import { applyDebugIds, buildCrashJson, @@ -79,6 +79,14 @@ function crashOf(value: unknown, origins?: AsyncOriginReporting): CrashJson { }); } +/** The frame an `error` event with no thrown value knows about: its `filename:lineno:colno`, path-scrubbed and + * stamped with the source-map debug-ID of the bundle it names (when a build injected one). */ +function errorEventFrame(event: ErrorEvent): StackFrame { + const frame = parseLocation(`${event.filename}:${event.lineno}:${event.colno}`); + applyDebugIds([frame], { parseStack }); + return frame; +} + /** * The crash for an `error` event. Prefer the thrown value; when the event carries none — a cross-origin * "Script error." has no `.error` — synthesise the exception from what the EVENT knows (its message and @@ -89,17 +97,27 @@ function crashOfErrorEvent(event: ErrorEvent, origins?: AsyncOriginReporting): C if (event.error != null) { return crashOf(event.error, origins); } - const crash = crashOf(new Error(event.message)); - crash.exception.name = 'Error'; if (event.filename) { - const frame = parseLocation(`${event.filename}:${event.lineno}:${event.colno}`); - crash.exception.frames = [{ trace: formatStack([frame]).trim(), user: true }]; - } else { - // A cross-origin "Script error." has neither a thrown value nor a filename, and the page cannot learn - // more (hiding that is the point of the restriction). An issue is grouped on its frames, so ZERO - // frames made every occurrence an issue of its own. One fixed frame makes them one issue. - crash.exception.frames = [{ trace: 'at ', user: true }]; + // As a caller-site frame of a non-Error, so it takes the SAME conversion a real stack's frames do: the structured + // position AND the `debug_id` the worker symbolicates by (a hand-built `{ trace, user }` carried neither). + const crash = buildCrashJson( + { message: event.message }, + { parseStack, handled: false, syntheticFrames: [errorEventFrame(event)] }, + ); + crash.exception.name = 'Error'; + if (!event.message) { + // The carrier object has no message to show, and its JSON would be shipped as the reason instead. + delete crash.exception.reason; + } + return crash; } + // A cross-origin "Script error." has neither a thrown value nor a filename, and the page cannot learn + // more (hiding that is the point of the restriction). An issue is grouped on its frames, so ZERO + // frames made every occurrence an issue of its own. One fixed frame makes them one issue. There is + // no file, so nothing to symbolicate and no debug-id to attach. + const crash = crashOf(new Error(event.message)); + crash.exception.name = 'Error'; + crash.exception.frames = [{ trace: 'at ', user: true }]; return crash; } @@ -115,8 +133,7 @@ function describeErrorEvent( } const summary = event.message; if (event.filename) { - const frame = parseLocation(`${event.filename}:${event.lineno}:${event.colno}`); - return { summary, description: formatStack([frame]) }; + return { summary, description: formatStack([errorEventFrame(event)]) }; } return { summary }; } diff --git a/packages/core/src/client.test.ts b/packages/core/src/client.test.ts index 560cd324..8cf0fd3b 100644 --- a/packages/core/src/client.test.ts +++ b/packages/core/src/client.test.ts @@ -912,6 +912,35 @@ describe('createClient — crash.json', () => { expect(members.some((m: string | undefined) => m?.includes('logException'))).toBe(false); }); + it.each([ + ['false', false], + ['a plain object (an Angular HttpErrorResponse)', { status: 500 }], + ['a string', 'payment failed'], + ])('stamps the debug_id of the caller’s bundle onto the frames of a thrown NON-Error: %s', async (_label, thrown) => { + // The injected build stub registers `new Error().stack` per bundle; its top frame is the bundle's own file, which is + // THIS file here. The worker symbolicates by per-frame `debug_id` and a frame without one ships minified, with + // the report still `ready`: this is the shape of an Angular `ErrorHandler` getting `false`. + const g = globalThis as { _bugseeDebugIds?: Record }; + const prev = g._bugseeDebugIds; + g._bugseeDebugIds = { [new Error().stack as string]: 'dbg-bundle' }; + try { + const { uploadPipeline, enqueue } = fakeUpload(); + const client = createClient({ uploadPipeline, appToken: 'tok', getEnvironment }); + async function applicationCode(): Promise { + await client.logException(thrown); + } + await applicationCode(); + const crash = crashOf(enqueue.mock.calls[0]?.[0] as Bundle); + const frame = crash.exception.frames.find( + (f: { data?: { member?: string } }) => f.data?.member === 'applicationCode', + ); + expect(frame?.debug_id).toBe('dbg-bundle'); + } finally { + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }); + it('skipFrames on a non-Error counts from the APPLICATION frame, not the SDK wrapper', async () => { const { uploadPipeline, enqueue } = fakeUpload(); const client = createClient({ uploadPipeline, appToken: 'tok', getEnvironment }); diff --git a/packages/core/src/crash.test.ts b/packages/core/src/crash.test.ts index 69038a16..8aa41613 100644 --- a/packages/core/src/crash.test.ts +++ b/packages/core/src/crash.test.ts @@ -90,6 +90,92 @@ describe('buildCrashJson', () => { expect(crash?.exception.frames[0]?.debug_id).toBe('dbg-uuid'); }); + describe('debug-ids on the caller-site frames of a thrown NON-Error', () => { + // `throw false`, `Promise.reject({...})`, an Angular `HttpErrorResponse`: the value has no stack, so the frames are the + // caller's (`callSiteFrames`). They are the ONLY frames the report has, and the worker symbolicates per frame by + // `debug_id`; a frame without one ships minified and the report still comes back `ready` (never `missing_sym`). + const registrationStack = 'Error\n at https://app.example/chunk-A.js:9:9'; + const globalObject = { _bugseeDebugIds: { [registrationStack]: 'dbg-A' } }; + const callSite = (): StackFrame[] => [ + { function: 'handleError', file: 'https://app.example/chunk-A.js', line: 3, column: 4 }, + { function: 'other', file: 'https://app.example/unregistered.js', line: 5, column: 6 }, + ]; + + it('stamps them when NO enricher is configured', () => { + const crash = buildCrashJson(false, { + parseStack: parseV8Stack, + globalObject, + syntheticFrames: callSite(), + }); + expect(crash.exception.frames.map((f) => f.debug_id)).toEqual(['dbg-A', undefined]); + }); + + it('stamps them when the enricher hands back the SAME array (the stamp must not hinge on identity)', () => { + const crash = buildCrashJson( + { status: 500 }, + { + parseStack: parseV8Stack, + globalObject, + syntheticFrames: callSite(), + enrichFrames: (_value, frames) => frames, + }, + ); + expect(crash.exception.frames.map((f) => f.debug_id)).toEqual(['dbg-A', undefined]); + }); + + it('stamps them when the enricher decorates them in place and returns the same array', () => { + const crash = buildCrashJson('payment failed', { + parseStack: parseV8Stack, + globalObject, + syntheticFrames: callSite(), + enrichFrames: (_value, frames) => { + for (const frame of frames) frame.variables = { seen: 'yes' }; + return frames; + }, + }); + expect(crash.exception.frames.map((f) => f.debug_id)).toEqual(['dbg-A', undefined]); + expect(crash.exception.frames[0]?.variables).toEqual({ seen: 'yes' }); + }); + + it('stamps the enricher’s replacement frames and the caller-site frames it dropped are not resurrected', () => { + const crash = buildCrashJson(0, { + parseStack: parseV8Stack, + globalObject, + syntheticFrames: callSite(), + enrichFrames: () => [ + { function: 'origin', file: 'https://app.example/chunk-A.js', line: 7, column: 8 }, + ], + }); + expect(crash.exception.frames.map((f) => [f.data?.line, f.debug_id])).toEqual([[7, 'dbg-A']]); + }); + + it('still ships the report, unstamped, when the stack parser throws while stamping', () => { + // `parseStack` is injected, and stamping parses every registered stack with it. Before stamping existed on this path a + // throwing parser was contained by `callSiteFrames`; it must not cost the report now. + const crash = buildCrashJson(false, { + parseStack: () => { + throw new Error('parser blew up'); + }, + globalObject, + syntheticFrames: callSite(), + enrichFrames: (_value, frames) => [...frames], + }); + expect(crash.exception.name).toBe('Boolean'); + expect(crash.exception.reason).toBe('false'); + expect(crash.exception.frames.map((f) => f.data?.line)).toEqual([3, 5]); + expect(crash.exception.frames.every((f) => f.debug_id === undefined)).toBe(true); + }); + + it('ships no debug_id when the build injected none', () => { + const crash = buildCrashJson(false, { + parseStack: parseV8Stack, + globalObject: {}, + syntheticFrames: callSite(), + }); + expect(crash.exception.frames.every((f) => f.debug_id === undefined)).toBe(true); + }); + }); + it('tells an enricher how deep in the cause chain it is (0 = the reported error), so it can act on the reported error only', () => { const calls: Array<{ message: string; depth: number | undefined }> = []; const inner = errorWith('Error', 'inner', 'Error: inner\n at i (a.js:1:1)'); @@ -126,6 +212,34 @@ describe('buildCrashJson', () => { expect(crash?.exception.cause?.frames[0]?.trace).toBe('at f (a.js:2:2)'); }); + it('stamps the debug_id on EVERY link of the cause chain, not just the reported error', () => { + // The cause is often the frame that matters (and a React component stack rides in as one): the worker + // symbolicates each link by its own per-frame `debug_id`. + const registrationStack = 'Error\n at reg (https://app.example/chunk-A.js:9:9)'; + const globalObject = { _bugseeDebugIds: { [registrationStack]: 'dbg-A' } }; + const root = errorWith( + 'Error', + 'root', + 'Error: root\n at r (https://app.example/chunk-A.js:1:1)', + ); + const mid = errorWith( + 'Error', + 'mid', + 'Error: mid\n at m (https://app.example/other.js:2:2)', + ); + const outer = errorWith( + 'Error', + 'outer', + 'Error: outer\n at o (https://app.example/chunk-A.js:3:3)', + ); + (mid as { cause?: unknown }).cause = root; + (outer as { cause?: unknown }).cause = mid; + const crash = buildCrashJson(outer, { parseStack: parseV8Stack, globalObject }); + expect(crash.exception.frames[0]?.debug_id).toBe('dbg-A'); + expect(crash.exception.cause?.frames[0]?.debug_id).toBeUndefined(); // other.js registered nothing + expect(crash.exception.cause?.cause?.frames[0]?.debug_id).toBe('dbg-A'); + }); + it('guards a cause CYCLE (self-cause does not recurse / loop)', () => { const err = errorWith('Error', 'x', 'Error: x\n at f (a.js:1:1)'); (err as { cause?: unknown }).cause = err; diff --git a/packages/core/src/crash.ts b/packages/core/src/crash.ts index 42a63117..39489a39 100644 --- a/packages/core/src/crash.ts +++ b/packages/core/src/crash.ts @@ -249,9 +249,22 @@ function buildException( } /** - * Build the structured crash.json container from a thrown value. A non-Error gets a SYNTHETIC - * exception rather than nothing at all — see {@link syntheticException}. + * Stamp debug-ids onto a synthetic exception's frames, CONTAINED. Stamping parses every registered stack with the + * injected `parseStack`; a parser that throws must cost the stamp, never the report. This path's frames used to be + * parsed only inside `callSiteFrames`, which contains a failing parser, so an unguarded stamp would be a new way to lose + * the report of a value that had no stack in the first place. */ +function stampDebugIds( + frames: StackFrame[], + stamp: { globalObject: unknown; parseStack: (stack: string) => StackFrame[] }, +): void { + try { + applyDebugIds(frames, stamp); + } catch { + // unstamped frames still ship; the worker falls back to the verbatim trace + } +} + /** * The exception for a value that is NOT an Error. * @@ -270,17 +283,22 @@ function buildException( function syntheticException( value: unknown, frames: StackFrame[] = [], - enrichFrames?: FrameEnricher, - stamp?: { globalObject: unknown; parseStack: (stack: string) => StackFrame[] }, + enrichFrames: FrameEnricher | undefined, + stamp: { globalObject: unknown; parseStack: (stack: string) => StackFrame[] }, ): CrashException { // The enricher runs here too. It used to run only on the Error path, so `logException('payment // failed')` shipped frames with neither locals nor source context — on the one path where the frames // are the CALLER's own and a report-site capture lines up with them exactly. Offered even with NO frames: an enricher may SUPPLY them // (async-origin capture gives a cross-realm DOMException, which is not `instanceof Error`, its call site), and a frameless report has // no grouping signature at all. An enricher with nothing for a bare value returns it unchanged. + // The caller-site frames are stamped BEFORE the enricher sees them, exactly as `buildException` stamps `parsed`: the + // worker symbolicates by per-frame `debug_id` and a frame without one ships minified, with the report still `ready`. + // Stamping only the enricher's replacement (`enriched !== frames`) left the common case, frames passed through + // untouched, unstamped. + stampDebugIds(frames, stamp); const enriched = enrichFrames !== undefined ? enrichFrames(value, frames, { depth: 0 }) : frames; - if (enriched !== frames && stamp !== undefined) { - applyDebugIds(enriched, stamp); // see buildException: the worker signs after symbolicating by debug_id + if (enriched !== frames) { + stampDebugIds(enriched, stamp); // frames an enricher SUPPLIED were never stamped above } // Through the SAME conversion a real Error's frames take, so a synthetic frame is indistinguishable // downstream: it carries `trace`, the `user` classification and any debug-id, and symbolicates the @@ -414,6 +432,10 @@ export function applyExceptionOptions( return crash; } +/** + * Build the structured crash.json container from a thrown value. A non-Error gets a SYNTHETIC + * exception rather than nothing at all — see {@link syntheticException}. + */ export function buildCrashJson(error: unknown, options: BuildCrashOptions = {}): CrashJson { if (!(error instanceof Error)) { return { diff --git a/packages/node/src/detection-providers.test.ts b/packages/node/src/detection-providers.test.ts index 94b7162e..554a7c7b 100644 --- a/packages/node/src/detection-providers.test.ts +++ b/packages/node/src/detection-providers.test.ts @@ -202,3 +202,48 @@ describe('detection providers — the frame enricher', () => { expect(crash?.exception.frames[0]).not.toHaveProperty('variables'); }); }); + +describe('debug-ids on node crash frames', () => { + // The worker symbolicates per frame by `debug_id`; a frame without one ships minified and the report still comes + // back `ready`. The stub a build injects registers `new Error().stack` per bundle, keyed by its top frame's file. + const withRegistered = (fn: () => void) => { + const g = globalThis as { _bugseeDebugIds?: Record }; + const prev = g._bugseeDebugIds; + g._bugseeDebugIds = { 'Error\n at reg (file:///app/work.js:1:1)': 'dbg-node' }; + try { + fn(); + } finally { + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }; + + it.each([ + ['uncaughtException', createUncaughtExceptionProvider], + ['unhandledRejection', createUnhandledRejectionProvider], + ] as const)('stamps the frames of an Error on %s', (event, create) => { + withRegistered(() => { + const p = fakeProcess(); + const requests = started(create(p.proc)); + const err = new Error('boom'); + err.stack = 'Error: boom\n at doWork (file:///app/work.js:3:7)'; // ESM: a file:// URL + p.emit(event, err); + const crash = requests[0]?.report.crash as CrashJson; + expect(crash.exception.frames[0]?.debug_id).toBe('dbg-node'); + }); + }); + + it('stamps the frames an enricher supplies for a rejected NON-Error', () => { + withRegistered(() => { + const p = fakeProcess(); + const requests = started( + createUnhandledRejectionProvider(p.proc, () => [ + { function: 'origin', file: '/app/work.js', line: 9, column: 1 }, + ]), + ); + p.emit('unhandledRejection', false); + const crash = requests[0]?.report.crash as CrashJson; + expect(crash.exception.frames[0]?.debug_id).toBe('dbg-node'); + }); + }); +}); diff --git a/packages/node/src/hang-stack.test.ts b/packages/node/src/hang-stack.test.ts index 67f6f5a0..6b8cb9ba 100644 --- a/packages/node/src/hang-stack.test.ts +++ b/packages/node/src/hang-stack.test.ts @@ -264,3 +264,33 @@ describe('hangCrashFromProfile', () => { expect(hangCrashFromProfile(p, opts)?.exception.frames[0]?.data?.member).toBe('parse'); }); }); + +describe('hangCrashFromProfile — debug-ids', () => { + // The profiler reports `file://` URLs and the registration stub's `Error().stack` carries either a URL (ESM) or a raw + // path (CommonJS). Both are normalised by the frame parser to ONE key, so the hang's frames still join their source map. + const withRegistered = (registration: string, fn: () => void) => { + const g = globalThis as { _bugseeDebugIds?: Record }; + const prev = g._bugseeDebugIds; + g._bugseeDebugIds = { [registration]: 'dbg-hang' }; + try { + fn(); + } finally { + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }; + + it.each([ + ['an ESM bundle (file:// URL)', 'Error\n at reg (file:///srv/lib.js:1:1)'], + ['a CommonJS bundle (raw path)', 'Error\n at reg (/srv/lib.js:1:1)'], + ])('stamps the blocking frame of %s', (_label, registration) => { + withRegistered(registration, () => { + const crash = hangCrashFromProfile(profile(TREE, [3, 3, 3, 5]), opts); + const byMember = Object.fromEntries( + (crash?.exception.frames ?? []).map((f) => [f.data?.member, f.debug_id]), + ); + expect(byMember.parse).toBe('dbg-hang'); // lib.js + expect(byMember.main).toBeUndefined(); // app.js registered nothing + }); + }); +}); diff --git a/packages/vercel-edge/src/detection.test.ts b/packages/vercel-edge/src/detection.test.ts index 3f94edab..01294156 100644 --- a/packages/vercel-edge/src/detection.test.ts +++ b/packages/vercel-edge/src/detection.test.ts @@ -114,3 +114,23 @@ describe('createEdgeUnhandledRejectionProvider', () => { expect(() => provider.stop()).not.toThrow(); }); }); + +describe('createEdgeUnhandledRejectionProvider — debug-ids', () => { + it('stamps the V8 frames of the reason with the debug-id its bundle registered', () => { + const g = globalThis as { _bugseeDebugIds?: Record }; + const prev = g._bugseeDebugIds; + g._bugseeDebugIds = { 'Error\n at reg (worker.js:1:1)': 'dbg-edge' }; + try { + const t = fakeTarget(); + const requests = start(createEdgeUnhandledRejectionProvider(t.target)); + const err = new Error('rejected'); + err.stack = 'Error: rejected\n at handler (worker.js:5:9)'; + t.emit('unhandledrejection', { reason: err }); + const crash = requests[0]?.report.crash as CrashJson; + expect(crash.exception.frames[0]?.debug_id).toBe('dbg-edge'); + } finally { + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }); +});