Skip to content
Draft
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
41 changes: 41 additions & 0 deletions packages/browser-utils/src/domEventNormalizer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { addNormalizeUnpacker, isInstanceOf } from '@sentry/core';
import { serializeEventTarget } from './object';

let unregister: (() => void) | undefined;

/**
* Registers a `normalize()` unpacker that extracts the meaningful fields of a DOM
* `Event` (`type`, `target`, `currentTarget`, optional `detail`) into a plain object
* before `normalize()` walks it. Element targets are serialized via `htmlTreeAsString`
* so the user sees a CSS-selector-style path rather than `[object HTMLButtonElement]`.
*
* Idempotent — calling more than once is a no-op (the existing registration is reused).
*
* Returns the unregister function from `addNormalizeUnpacker` (useful for tests).
*/
export function registerDomEventNormalizer(): () => void {
if (unregister) {
return unregister;
}
unregister = addNormalizeUnpacker(value => {
if (typeof Event === 'undefined' || !(value instanceof Event)) {
return undefined;
}
const result: Record<string, unknown> = {
type: value.type,
target: serializeEventTarget(value.target),
currentTarget: serializeEventTarget(value.currentTarget),
...Object.fromEntries(Object.entries(value)),
};
if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
result.detail = (value as CustomEvent).detail;
}
return result;
});

const baseUnregister = unregister;
return () => {
baseUnregister();
unregister = undefined;
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Idempotent unregister breaks re-registration

Medium Severity

When registerDomEventNormalizer() runs while a registration already exists, it returns the raw addNormalizeUnpacker teardown instead of the wrapper that clears module state. Calling that teardown removes the unpacker but leaves the module unregister reference set, so later calls hit the idempotent branch and never call addNormalizeUnpacker again—DOM Event normalization stays off until the module reloads.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3ed69bb. Configure here.

}
124 changes: 124 additions & 0 deletions packages/browser-utils/src/htmlTreeAsString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { isString } from '@sentry/core';

const DEFAULT_MAX_STRING_LENGTH = 80;

type SimpleNode = {
parentNode: SimpleNode;
} | null;

/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @returns generated DOM path
*/
export function htmlTreeAsString(
elem: unknown,
options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},
): string {
if (!elem) {
return '<unknown>';
}

// try/catch both:
// - accessing event.target (see getsentry/raven-js#838, #768)
// - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly
// - can throw an exception in some circumstances.
try {
let currentElem = elem as SimpleNode;
const MAX_TRAVERSE_HEIGHT = 5;
const out = [];
let height = 0;
let len = 0;
const separator = ' > ';
const sepLength = separator.length;
let nextStr;
const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;
const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;

while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = _htmlElementAsString(currentElem, keyAttrs);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds maxStringLength
// (ignore this limit if we are on the first iteration)
if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {
break;
}

out.push(nextStr);

len += nextStr.length;
currentElem = currentElem.parentNode;
}

return out.reverse().join(separator);
} catch {
return '<unknown>';
}
}

/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @returns generated DOM path
*/
function _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {
const elem = el as {
tagName?: string;
id?: string;
className?: string;
getAttribute(key: string): string;
};

const out = [];

if (!elem?.tagName) {
return '';
}

if (typeof HTMLElement !== 'undefined') {
// If using the component name annotation plugin, this value may be available on the DOM node
if (elem instanceof HTMLElement && elem.dataset) {
if (elem.dataset['sentryComponent']) {
return elem.dataset['sentryComponent'];
}
if (elem.dataset['sentryElement']) {
return elem.dataset['sentryElement'];
}
}
}

out.push(elem.tagName.toLowerCase());

// Pairs of attribute keys defined in `serializeAttribute` and their values on element.
const keyAttrPairs = keyAttrs?.length
? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])
: null;

if (keyAttrPairs?.length) {
keyAttrPairs.forEach(keyAttrPair => {
out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
});
} else {
if (elem.id) {
out.push(`#${elem.id}`);
}

const className = elem.className;
if (className && isString(className)) {
const classes = className.split(/\s+/);
for (const c of classes) {
out.push(`.${c}`);
}
}
}
for (const k of ['aria-label', 'type', 'name', 'title', 'alt']) {
const attr = elem.getAttribute(k);
if (attr) {
out.push(`[${k}="${attr}"]`);
}
}

return out.join('');
}
6 changes: 6 additions & 0 deletions packages/browser-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,10 @@ export { getBodyString, getFetchRequestArgBody, serializeFormData, parseXhrRespo

export { resourceTimingToSpanAttributes } from './metrics/resourceTiming';

export { convertToPlainObject, extractExceptionKeysForMessage } from './object';

export { htmlTreeAsString } from './htmlTreeAsString';

export { registerDomEventNormalizer } from './domEventNormalizer';

export type { FetchHint, NetworkMetaWarning, XhrHint } from './types';
2 changes: 1 addition & 1 deletion packages/browser-utils/src/metrics/browserMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import {
debug,
getActiveSpan,
getComponentName,
htmlTreeAsString,
isPrimitive,
parseUrl,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
setMeasurement,
spanToJSON,
stringMatchesSomePattern,
} from '@sentry/core';
import { htmlTreeAsString } from '../htmlTreeAsString';
import { WINDOW } from '../types';
import { trackClsAsStandaloneSpan } from './cls';
import {
Expand Down
2 changes: 1 addition & 1 deletion packages/browser-utils/src/metrics/cls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
browserPerformanceTimeOrigin,
debug,
getCurrentScope,
htmlTreeAsString,
SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,
SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT,
SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE,
Expand All @@ -12,6 +11,7 @@ import {
timestampInSeconds,
} from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';
import { htmlTreeAsString } from '../htmlTreeAsString';
import { addClsInstrumentationHandler } from './instrument';
import type { WebVitalReportEvent } from './utils';
import { listenForWebVitalReportEvents, msToSec, startStandaloneWebVitalSpan, supportsWebVital } from './utils';
Expand Down
2 changes: 1 addition & 1 deletion packages/browser-utils/src/metrics/inp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
getActiveSpan,
getCurrentScope,
getRootSpan,
htmlTreeAsString,
isBrowser,
SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,
SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT,
Expand All @@ -13,6 +12,7 @@ import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
spanToJSON,
} from '@sentry/core';
import { htmlTreeAsString } from '../htmlTreeAsString';
import { WINDOW } from '../types';
import type { InstrumentationHandlerCallback } from './instrument';
import {
Expand Down
2 changes: 1 addition & 1 deletion packages/browser-utils/src/metrics/lcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import {
browserPerformanceTimeOrigin,
debug,
getCurrentScope,
htmlTreeAsString,
SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,
SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT,
SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
} from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';
import { htmlTreeAsString } from '../htmlTreeAsString';
import { addLcpInstrumentationHandler } from './instrument';
import type { WebVitalReportEvent } from './utils';
import { listenForWebVitalReportEvents, msToSec, startStandaloneWebVitalSpan, supportsWebVital } from './utils';
Expand Down
2 changes: 1 addition & 1 deletion packages/browser-utils/src/metrics/webVitalSpans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import {
getActiveSpan,
getCurrentScope,
getRootSpan,
htmlTreeAsString,
SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
spanToStreamedSpanJSON,
startInactiveSpan,
timestampInSeconds,
} from '@sentry/core';
import { htmlTreeAsString } from '../htmlTreeAsString';
import { DEBUG_BUILD } from '../debug-build';
import { WINDOW } from '../types';
import { getCachedInteractionContext, INP_ENTRY_MAP, MAX_PLAUSIBLE_INP_DURATION } from './inp';
Expand Down
79 changes: 79 additions & 0 deletions packages/browser-utils/src/object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { isElement, isEvent, isInstanceOf, convertToPlainObject as originalConvertToPlainObject } from '@sentry/core';
import { htmlTreeAsString } from './htmlTreeAsString';

/**
* Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
* non-enumerable properties attached.
*
* @param value Initial source that we have to transform in order for it to be usable by the serializer
* @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor
* an Error.
*/
export function convertToPlainObject<V>(value: V):
| {
[ownProps: string]: unknown;
type: string;
target: string;
currentTarget: string;
detail?: unknown;
}
| {
[ownProps: string]: unknown;
message: string;
name: string;
stack?: string;
}
| V {
if (isEvent(value)) {
const newObj: {
[ownProps: string]: unknown;
type: string;
target: string;
currentTarget: string;
detail?: unknown;
} = {
type: value.type,
target: serializeEventTarget(value.target),
currentTarget: serializeEventTarget(value.currentTarget),
...getOwnProperties(value),
};

if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
newObj.detail = value.detail;
}

return newObj;
}

return originalConvertToPlainObject(value);
}

export function serializeEventTarget(target: unknown): string {
try {
return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
} catch {
return '<unknown>';
}
}

function getOwnProperties(obj: unknown): { [key: string]: unknown } {
if (typeof obj === 'object' && obj !== null) {
return Object.fromEntries(Object.entries(obj));
}
return {};
}

/**
* Given any captured exception, extract its keys and create a sorted
* and truncated list that will be used inside the event message.
* eg. `Non-error exception captured with keys: foo, bar, baz`
*
* The browser variant produces richer output for `Event` exceptions
* (e.g. extracting `type`, `target`, `currentTarget`).
*/
export function extractExceptionKeysForMessage(exception: Record<string, unknown>): string {
const keys = Object.keys(convertToPlainObject(exception));
keys.sort();

return !keys[0] ? '[object has no keys]' : keys.join(', ');
}
Loading
Loading