Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .changeset/stamp-debug-ids-on-synthetic-frames.md
Original file line number Diff line number Diff line change
@@ -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.
72 changes: 72 additions & 0 deletions packages/browser/src/detection-providers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> };
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 <anonymous> (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<string, string> };
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));
Expand Down
41 changes: 29 additions & 12 deletions packages/browser/src/detection-providers.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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 <cross-origin script>', 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)] },
Comment thread
krassx marked this conversation as resolved.
Resolved
);
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 <cross-origin script>', user: true }];
return crash;
}

Expand All @@ -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 };
}
Expand Down
29 changes: 29 additions & 0 deletions packages/core/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> };
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<void> {
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 });
Expand Down
114 changes: 114 additions & 0 deletions packages/core/src/crash.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)');
Expand Down Expand Up @@ -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;
Expand Down
34 changes: 28 additions & 6 deletions packages/core/src/crash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading