{"version":3,"file":"bundle.min.js","sources":["../../types/src/severity.ts","../../utils/src/global.ts","../../utils/src/is.ts","../../utils/src/browser.ts","../../utils/src/polyfill.ts","../../utils/src/error.ts","../../utils/src/dsn.ts","../../utils/src/enums.ts","../../utils/src/logger.ts","../../utils/src/stacktrace.ts","../../utils/src/string.ts","../../utils/src/object.ts","../../utils/src/memo.ts","../../utils/src/supports.ts","../../utils/src/instrument.ts","../../utils/src/env.ts","../../utils/src/misc.ts","../../utils/src/syncpromise.ts","../../utils/src/promisebuffer.ts","../../utils/src/severity.ts","../../utils/src/time.ts","../../hub/src/scope.ts","../../hub/src/session.ts","../../hub/src/hub.ts","../../minimal/src/index.ts","../../core/src/api.ts","../../core/src/integration.ts","../../core/src/baseclient.ts","../../core/src/transports/noop.ts","../../core/src/basebackend.ts","../../core/src/request.ts","../../core/src/integrations/functiontostring.ts","../../core/src/version.ts","../../core/src/integrations/inboundfilters.ts","../src/stack-parsers.ts","../src/parsers.ts","../src/eventbuilder.ts","../src/transports/utils.ts","../../utils/src/async.ts","../src/transports/base.ts","../../utils/src/clientreport.ts","../../utils/src/envelope.ts","../../utils/src/status.ts","../src/transports/fetch.ts","../src/transports/xhr.ts","../src/backend.ts","../src/helpers.ts","../src/integrations/globalhandlers.ts","../src/integrations/trycatch.ts","../src/integrations/breadcrumbs.ts","../src/integrations/linkederrors.ts","../src/integrations/useragent.ts","../src/integrations/dedupe.ts","../src/client.ts","../src/sdk.ts","../src/index.ts","../src/version.ts","../../core/src/sdk.ts"],"sourcesContent":["/**\n * TODO(v7): Remove this enum and replace with SeverityLevel\n */\nexport enum Severity {\n /** JSDoc */\n Fatal = 'fatal',\n /** JSDoc */\n Error = 'error',\n /** JSDoc */\n Warning = 'warning',\n /** JSDoc */\n Log = 'log',\n /** JSDoc */\n Info = 'info',\n /** JSDoc */\n Debug = 'debug',\n /** JSDoc */\n Critical = 'critical',\n}\n\n// TODO: in v7, these can disappear, because they now also exist in `@sentry/utils`. (Having them there rather than here\n// is nice because then it enforces the idea that only types are exported from `@sentry/types`.)\nexport const SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical'] as const;\nexport type SeverityLevel = typeof SeverityLevels[number];\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { Integration } from '@sentry/types';\n\nimport { isNodeEnv } from './node';\n\n/** Internal */\ninterface SentryGlobal {\n Sentry?: {\n Integrations?: Integration[];\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n };\n}\n\nconst fallbackGlobalObject = {};\n\n/**\n * Safely get global scope object\n *\n * @returns Global scope object\n */\nexport function getGlobalObject(): T & SentryGlobal {\n return (\n isNodeEnv()\n ? global\n : typeof window !== 'undefined' // eslint-disable-line no-restricted-globals\n ? window // eslint-disable-line no-restricted-globals\n : typeof self !== 'undefined'\n ? self\n : fallbackGlobalObject\n ) as T & SentryGlobal;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport { Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): boolean {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n\nfunction isBuiltin(wat: unknown, ty: string): boolean {\n return objectToString.call(wat) === `[object ${ty}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): boolean {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): boolean {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n","import { getGlobalObject } from './global';\nimport { isString } from './is';\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(elem: unknown, keyAttrs?: string[]): string {\n type SimpleNode = {\n parentNode: SimpleNode;\n } | null;\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const MAX_OUTPUT_LEN = 80;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n\n // eslint-disable-next-line no-plusplus\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds MAX_OUTPUT_LEN\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n const global = getGlobalObject();\n try {\n return global.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n","export const setPrototypeOf =\n Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);\n\n/**\n * setPrototypeOf polyfill using __proto__\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction setProtoOf(obj: TTarget, proto: TProto): TTarget & TProto {\n // @ts-ignore __proto__ does not exist on obj\n obj.__proto__ = proto;\n return obj as TTarget & TProto;\n}\n\n/**\n * setPrototypeOf polyfill using mixin\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction mixinProperties(obj: TTarget, proto: TProto): TTarget & TProto {\n for (const prop in proto) {\n if (!Object.prototype.hasOwnProperty.call(obj, prop)) {\n // @ts-ignore typescript complains about indexing so we remove\n obj[prop] = proto[prop];\n }\n }\n\n return obj as TTarget & TProto;\n}\n","import { setPrototypeOf } from './polyfill';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public constructor(public message: string) {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { isDebugBuild } from './env';\nimport { SentryError } from './error';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+))?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\nfunction dsnFromString(str: string): DsnComponents {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new SentryError(`Invalid Sentry Dsn: ${str}`);\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n // TODO this is for backwards compatibility, and can be removed in a future version\n if ('user' in components && !('publicKey' in components)) {\n components.publicKey = components.user;\n }\n\n return {\n user: components.publicKey || '',\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean | void {\n if (!isDebugBuild()) {\n return;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n requiredComponents.forEach(component => {\n if (!dsn[component]) {\n throw new SentryError(`Invalid Sentry Dsn: ${component} missing`);\n }\n });\n\n if (!projectId.match(/^\\d+$/)) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n }\n\n if (!isValidProtocol(protocol)) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid port ${port}`);\n }\n\n return true;\n}\n\n/** The Sentry Dsn, identifying a Sentry instance and project. */\nexport function makeDsn(from: DsnLike): DsnComponents {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n\n validateDsn(components);\n\n return components;\n}\n","export const SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical'] as const;\nexport type SeverityLevel = typeof SeverityLevels[number];\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\n\n// TODO: Implement different loggers for different environments\nconst global = getGlobalObject();\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\n/** JSDoc */\ninterface ExtensibleConsole extends Console {\n [key: string]: any;\n}\n\n/**\n * Temporarily unwrap `console.log` and friends in order to perform the given callback using the original methods.\n * Restores wrapping after the callback completes.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => any): any {\n const global = getGlobalObject();\n const levels = ['debug', 'info', 'warn', 'error', 'log', 'assert'];\n\n if (!('console' in global)) {\n return callback();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const originalConsole = (global as any).console as ExtensibleConsole;\n const wrappedLevels: { [key: string]: any } = {};\n\n // Restore all wrapped console methods\n levels.forEach(level => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (level in (global as any).console && (originalConsole[level] as WrappedFunction).__sentry_original__) {\n wrappedLevels[level] = originalConsole[level] as WrappedFunction;\n originalConsole[level] = (originalConsole[level] as WrappedFunction).__sentry_original__;\n }\n });\n\n // Perform callback manipulations\n const result = callback();\n\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level];\n });\n\n return result;\n}\n\n/** JSDoc */\nclass Logger {\n /** JSDoc */\n private _enabled: boolean;\n\n /** JSDoc */\n public constructor() {\n this._enabled = false;\n }\n\n /** JSDoc */\n public disable(): void {\n this._enabled = false;\n }\n\n /** JSDoc */\n public enable(): void {\n this._enabled = true;\n }\n\n /** JSDoc */\n public log(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.log(`${PREFIX}[Log]: ${args.join(' ')}`);\n });\n }\n\n /** JSDoc */\n public warn(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.warn(`${PREFIX}[Warn]: ${args.join(' ')}`);\n });\n }\n\n /** JSDoc */\n public error(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.error(`${PREFIX}[Error]: ${args.join(' ')}`);\n });\n }\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nglobal.__SENTRY__ = global.__SENTRY__ || {};\nconst logger = (global.__SENTRY__.logger as Logger) || (global.__SENTRY__.logger = new Logger());\n\nexport { logger };\n","import { StackFrame } from '@sentry/types';\n\nconst STACKTRACE_LIMIT = 50;\n\nexport type StackLineParser = (line: string) => StackFrame | undefined;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n * */\nexport function createStackParser(...parsers: StackLineParser[]) {\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n\n for (const line of stack.split('\\n').slice(skipFirst)) {\n for (const parser of parsers) {\n const frame = parser(line);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: StackFrame[]): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n let localStack = stack;\n\n const firstFrameFunction = localStack[0].function || '';\n const lastFrameFunction = localStack[localStack.length - 1].function || '';\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {\n localStack = localStack.slice(1);\n }\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (lastFrameFunction.indexOf('sentryWrapped') !== -1) {\n localStack = localStack.slice(0, -1);\n }\n\n // The frame where the crash happened, should be the last entry in the array\n return localStack\n .slice(0, STACKTRACE_LIMIT)\n .map(frame => ({\n ...frame,\n filename: frame.filename || localStack[0].filename,\n function: frame.function || '?',\n }))\n .reverse();\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n","import { isRegExp, isString } from './is';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.substr(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the value matches a regex or includes the string\n * @param value The string value to be checked against\n * @param pattern Either a regex or a string that must be contained in value\n */\nexport function isMatchingPattern(value: string, pattern: RegExp | string): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return (pattern as RegExp).test(value);\n }\n if (typeof pattern === 'string') {\n return value.indexOf(pattern) !== -1;\n }\n return false;\n}\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime\n * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node\n * 12+).\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nexport function escapeStringForRegex(regexString: string): string {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { ExtendedError, WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive, isSyntheticEvent } from './is';\nimport { memoBuilder, MemoFunc } from './memo';\nimport { getFunctionName } from './stacktrace';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: { [key: string]: unknown }, name: string, value: unknown): void {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any object into an object literal with all its attributes\n * attached to it.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n */\nfunction getWalkSource(value: any): {\n [key: string]: any;\n} {\n if (isError(value)) {\n const error = value as ExtendedError;\n const err: {\n [key: string]: any;\n stack: string | undefined;\n message: string;\n name: string;\n } = {\n message: error.message,\n name: error.name,\n stack: error.stack,\n };\n\n for (const i in error) {\n if (Object.prototype.hasOwnProperty.call(error, i)) {\n err[i] = error[i];\n }\n }\n\n return err;\n }\n\n if (isEvent(value)) {\n /**\n * Event-like interface that's usable in browser and node\n */\n interface SimpleEvent {\n [key: string]: unknown;\n type: string;\n target?: unknown;\n currentTarget?: unknown;\n }\n\n const event = value as unknown as SimpleEvent;\n\n const source: {\n [key: string]: any;\n } = {};\n\n // Accessing event attributes can throw (see https://github.com/getsentry/sentry-javascript/issues/768 and\n // https://github.com/getsentry/sentry-javascript/issues/838), but accessing `type` hasn't been wrapped in a\n // try-catch in at least two years and no one's complained, so that's likely not an issue anymore\n source.type = event.type;\n\n try {\n source.target = isElement(event.target)\n ? htmlTreeAsString(event.target)\n : Object.prototype.toString.call(event.target);\n } catch (_oO) {\n source.target = '';\n }\n\n try {\n source.currentTarget = isElement(event.currentTarget)\n ? htmlTreeAsString(event.currentTarget)\n : Object.prototype.toString.call(event.currentTarget);\n } catch (_oO) {\n source.currentTarget = '';\n }\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n source.detail = event.detail;\n }\n\n for (const attr in event) {\n if (Object.prototype.hasOwnProperty.call(event, attr)) {\n source[attr] = event[attr];\n }\n }\n\n return source;\n }\n\n return value as {\n [key: string]: any;\n };\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const serialized = normalize(object, depth);\n\n if (jsonSize(serialized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return serialized as T;\n}\n\n/**\n * Transform any non-primitive, BigInt, or Symbol-type value into a string. Acts as a no-op on strings, numbers,\n * booleans, null, and undefined.\n *\n * @param value The value to stringify\n * @returns For non-primitive, BigInt, and Symbol-type values, a string denoting the value's type, type and value, or\n * type and `description` property, respectively. For non-BigInt, non-Symbol primitives, returns the original value,\n * unchanged.\n */\nfunction serializeValue(value: any): any {\n // Node.js REPL notation\n if (typeof value === 'string') {\n return value;\n }\n\n const type = Object.prototype.toString.call(value);\n if (type === '[object Object]') {\n return '[Object]';\n }\n if (type === '[object Array]') {\n return '[Array]';\n }\n\n const normalized = normalizeValue(value);\n return isPrimitive(normalized) ? normalized : type;\n}\n\n/**\n * normalizeValue()\n *\n * Takes unserializable input and make it serializable friendly\n *\n * - translates undefined/NaN values to \"[undefined]\"/\"[NaN]\" respectively,\n * - serializes Error objects\n * - filter global objects\n */\nfunction normalizeValue(value: T, key?: any): T | string {\n if (key === 'domain' && value && typeof value === 'object' && (value as unknown as { _events: any })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n if (typeof (global as any) !== 'undefined' && (value as unknown) === global) {\n return '[Global]';\n }\n\n // It's safe to use `window` and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof (window as any) !== 'undefined' && (value as unknown) === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof (document as any) !== 'undefined' && (value as unknown) === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (value === void 0) {\n return '[undefined]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n // symbols and bigints are considered primitives by TS, but aren't natively JSON-serilaizable\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n return value;\n}\n\n/**\n * Walks an object to perform a normalization on it\n *\n * @param key of object that's walked in current iteration\n * @param value object to be walked\n * @param depth Optional number indicating how deep should walking be performed\n * @param memo Optional Memo class handling decycling\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function walk(key: string, value: any, depth: number = +Infinity, memo: MemoFunc = memoBuilder()): any {\n // If we reach the maximum depth, serialize whatever is left\n if (depth === 0) {\n return serializeValue(value);\n }\n\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // If value implements `toJSON` method, call it and return early\n if (value !== null && value !== undefined && typeof value.toJSON === 'function') {\n return value.toJSON();\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n // If normalized value is a primitive, there are no branches left to walk, so bail out\n const normalized = normalizeValue(value, key);\n if (isPrimitive(normalized)) {\n return normalized;\n }\n\n // Create source that we will use for the next iteration. It will either be an objectified error object (`Error` type\n // with extracted key:value pairs) or the input itself.\n const source = getWalkSource(value);\n\n // Create an accumulator that will act as a parent for all future itterations of that branch\n const acc = Array.isArray(value) ? [] : {};\n\n // If we already walked that branch, bail out, as it's circular reference\n if (memo[0](value)) {\n return '[Circular ~]';\n }\n\n // Walk all keys of the source\n for (const innerKey in source) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(source, innerKey)) {\n continue;\n }\n // Recursively walk through all the child nodes\n (acc as { [key: string]: any })[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo);\n }\n\n // Once walked through all the branches, remove the parent from memo storage\n memo[1](value);\n\n // Return accumulated values\n return acc;\n}\n\n/**\n * normalize()\n *\n * - Creates a copy to prevent original input mutation\n * - Skip non-enumerablers\n * - Calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format\n * - Translates known global objects/Classes to a string representations\n * - Takes care of Error objects serialization\n * - Optionally limit depth of final output\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function normalize(input: any, depth?: number): any {\n try {\n return JSON.parse(JSON.stringify(input, (key: string, value: any) => walk(key, value, depth)));\n } catch (_oO) {\n return '**non-serializable**';\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function extractExceptionKeysForMessage(exception: any, maxLength: number = 40): string {\n const keys = Object.keys(getWalkSource(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return the new object with removed keys that value was `undefined`.\n * Works recursively on objects and arrays.\n */\nexport function dropUndefinedKeys(val: T): T {\n if (isPlainObject(val)) {\n const obj = val as { [key: string]: any };\n const rv: { [key: string]: any } = {};\n for (const key of Object.keys(obj)) {\n if (typeof obj[key] !== 'undefined') {\n rv[key] = dropUndefinedKeys(obj[key]);\n }\n }\n return rv as T;\n }\n\n if (Array.isArray(val)) {\n return (val as any[]).map(dropUndefinedKeys) as any;\n }\n\n return val;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [(obj: any) => boolean, (obj: any) => void];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import { isDebugBuild } from './env';\nimport { getGlobalObject } from './global';\nimport { logger } from './logger';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in getGlobalObject())) {\n return false;\n }\n\n try {\n new Headers();\n new Request('');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (!supportsFetch()) {\n return false;\n }\n\n const global = getGlobalObject();\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(global.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = global.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === `function`) {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n if (isDebugBuild()) {\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in getGlobalObject();\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n const global = getGlobalObject();\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (global as any).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport { WrappedFunction } from '@sentry/types';\n\nimport { isDebugBuild } from './env';\nimport { getGlobalObject } from './global';\nimport { isInstanceOf, isString } from './is';\nimport { logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\n\nconst global = getGlobalObject();\n\ntype InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\ntype InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n logger.warn('unknown instrumentation type:', type);\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(type: InstrumentHandlerType, callback: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n if (isDebugBuild()) {\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(\n handler,\n )}\\nError: ${e}`,\n );\n }\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in global)) {\n return;\n }\n\n ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function (level: string): void {\n if (!(level in global.console)) {\n return;\n }\n\n fill(global.console, level, function (originalConsoleMethod: () => any): Function {\n return function (...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(global.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(global, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const handlerData = {\n args,\n fetchData: {\n method: getFetchMethod(args),\n url: getFetchUrl(args),\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(global, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\ntype XHRSendInput = null | Blob | BufferSource | FormData | URLSearchParams | string;\n\n/** JSDoc */\ninterface SentryWrappedXMLHttpRequest extends XMLHttpRequest {\n [key: string]: any;\n __sentry_xhr__?: {\n method?: string;\n url?: string;\n status_code?: number;\n body?: XHRSendInput;\n };\n}\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Extract `method` from fetch call arguments */\nfunction getFetchMethod(fetchArgs: any[] = []): string {\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {\n return String(fetchArgs[0].method).toUpperCase();\n }\n if (fetchArgs[1] && fetchArgs[1].method) {\n return String(fetchArgs[1].method).toUpperCase();\n }\n return 'GET';\n}\n\n/** Extract `url` from fetch call arguments */\nfunction getFetchUrl(fetchArgs: any[] = []): string {\n if (typeof fetchArgs[0] === 'string') {\n return fetchArgs[0];\n }\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request)) {\n return fetchArgs[0].url;\n }\n return String(fetchArgs[0]);\n}\n/* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n/** JSDoc */\nfunction instrumentXHR(): void {\n if (!('XMLHttpRequest' in global)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: SentryWrappedXMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const url = args[1];\n const xhrInfo: SentryWrappedXMLHttpRequest['__sentry_xhr__'] = (xhr.__sentry_xhr__ = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n xhr.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = function (): void {\n if (xhr.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = xhr.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args,\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr,\n });\n }\n };\n\n if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {\n fill(xhr, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(xhr, readyStateArgs);\n };\n });\n } else {\n xhr.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n return originalOpen.apply(xhr, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: SentryWrappedXMLHttpRequest, ...args: any[]): void {\n if (this.__sentry_xhr__ && args[0] !== undefined) {\n this.__sentry_xhr__.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = global.onpopstate;\n global.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = global.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(global.history, 'pushState', historyReplacementFunction);\n fill(global.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = global.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nfunction instrumentDOM(): void {\n if (!('document' in global)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n global.document.addEventListener('click', globalDOMEventHandler, false);\n global.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (global as any)[target] && (global as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount += 1;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount -= 1;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler: OnErrorEventHandler = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = global.onerror;\n\n global.onerror = function (msg: any, url: any, line: any, column: any, error: any): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n}\n\nlet _oldOnUnhandledRejectionHandler: ((e: any) => void) | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = global.onunhandledrejection;\n\n global.onunhandledrejection = function (e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n}\n","/**\n * This module mostly exists for optimizations in the build process\n * through rollup and terser. We define some global constants which\n * are normally undefined. However terser overrides these with global\n * definitions which can be evaluated by the static analyzer when\n * creating a bundle.\n *\n * In turn the `isDebugBuild` and `isBrowserBundle` functions are pure\n * and can help us remove unused code from the bundles.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\ndeclare const __SENTRY_NO_DEBUG__: boolean | undefined;\n\n/**\n * Figures out if we're building with debug functionality.\n *\n * @returns true if this is a debug build\n */\nexport function isDebugBuild(): boolean {\n return typeof __SENTRY_NO_DEBUG__ !== 'undefined' && !__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\n\n/**\n * Extended Window interface that allows for Crypto API usage in IE browsers\n */\ninterface MsCryptoWindow extends Window {\n msCrypto?: Crypto;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const global = getGlobalObject() as MsCryptoWindow;\n const crypto = global.crypto || global.msCrypto;\n\n if (!(crypto === void 0) && crypto.getRandomValues) {\n // Use window.crypto API if available\n const arr = new Uint16Array(8);\n crypto.getRandomValues(arr);\n\n // set 4 in byte 7\n // eslint-disable-next-line no-bitwise\n arr[3] = (arr[3] & 0xfff) | 0x4000;\n // set 2 most significant bits of byte 9 to '10'\n // eslint-disable-next-line no-bitwise\n arr[4] = (arr[4] & 0x3fff) | 0x8000;\n\n const pad = (num: number): string => {\n let v = num.toString(16);\n while (v.length < 4) {\n v = `0${v}`;\n }\n return v;\n };\n\n return (\n pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])\n );\n }\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {\n // eslint-disable-next-line no-bitwise\n const r = (Math.random() * 16) | 0;\n // eslint-disable-next-line no-bitwise\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n} {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\nconst defaultRetryAfter = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param now current unix timestamp\n * @param header string representation of 'Retry-After' header\n */\nexport function parseRetryAfterHeader(now: number, header?: string | number | null): number {\n if (!header) {\n return defaultRetryAfter;\n }\n\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return defaultRetryAfter;\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n const lineno = frame.lineno || 0;\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States = States.PENDING;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]> = [];\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import { SentryError } from './error';\nimport { rejectedSyncPromise, resolvedSyncPromise, SyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise due to buffer limit reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n // eslint-disable-next-line no-plusplus\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { Severity } from '@sentry/types';\n\nimport { SeverityLevel, SeverityLevels } from './enums';\n\nfunction isSupportedSeverity(level: string): level is Severity {\n return SeverityLevels.indexOf(level as SeverityLevel) !== -1;\n}\n/**\n * Converts a string-based level into a {@link Severity}.\n *\n * @param level string representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: SeverityLevel | string): Severity {\n if (level === 'warn') return Severity.Warning;\n if (isSupportedSeverity(level)) {\n return level;\n }\n return Severity.Log;\n}\n","import { getGlobalObject } from './global';\nimport { dynamicRequire, isNodeEnv } from './node';\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\ninterface TimestampSource {\n nowSeconds(): number;\n}\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource: TimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance(): Performance | undefined {\n const { performance } = getGlobalObject();\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance(): Performance | undefined {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: Performance };\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance: Performance | undefined = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource: TimestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport const dateTimestampInSeconds: () => number = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds: () => number = timestampSource.nowSeconds.bind(timestampSource);\n\n// Re-exported with an old name for backwards-compatibility.\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport const usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = getGlobalObject();\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","/* eslint-disable max-lines */\nimport {\n Breadcrumb,\n CaptureContext,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n Severity,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, getGlobalObject, isPlainObject, isThenable, SyncPromise } from '@sentry/utils';\n\nimport { Session } from './session';\n\n/**\n * Absolute maximum number of breadcrumbs added to an event.\n * The `maxBreadcrumbs` option cannot be higher than this value.\n */\nconst MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean = false;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void> = [];\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[] = [];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[] = [];\n\n /** User */\n protected _user: User = {};\n\n /** Tags */\n protected _tags: { [key: string]: Primitive } = {};\n\n /** Extra */\n protected _extra: Extras = {};\n\n /** Contexts */\n protected _contexts: Contexts = {};\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n protected _level?: Severity;\n\n /** Transaction Name */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata?: { [key: string]: unknown } = {};\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n public static clone(scope?: Scope): Scope {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n this._user = user || {};\n if (this._session) {\n this._session.update({ user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(level: Severity): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Can be removed in major version.\n * @deprecated in favor of {@link this.setTransactionName}\n */\n public setTransaction(name?: string): this {\n return this.setTransactionName(name);\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts = { ...this._contexts, [key]: context };\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext as (scope: T) => T)(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Applies the current context and fingerprint to the event.\n * Note that breadcrumbs will be added by the client.\n * Also if the event has already breadcrumbs on it, we do not merge them.\n * @param event Event\n * @param hint May contain additional information about the original exception.\n * @hidden\n */\n public applyToEvent(event: Event, hint?: EventHint): PromiseLike {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transactionName = this._span.transaction && this._span.transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = this._sdkProcessingMetadata;\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n protected _notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint?: EventHint,\n index: number = 0,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n if (isThenable(result)) {\n void (result as PromiseLike)\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n private _applyFingerprint(event: Event): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors(): EventProcessor[] {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n const global = getGlobalObject();\n global.__SENTRY__ = global.__SENTRY__ || {};\n global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || [];\n return global.__SENTRY__.globalEventProcessors;\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n getGlobalEventProcessors().push(callback);\n}\n","import { Session as SessionInterface, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * @inheritdoc\n */\nexport class Session implements SessionInterface {\n public userAgent?: string;\n public errors: number = 0;\n public release?: string;\n public sid: string = uuid4();\n public did?: string;\n public timestamp: number;\n public started: number;\n public duration?: number = 0;\n public status: SessionStatus = 'ok';\n public environment?: string;\n public ipAddress?: string;\n public init: boolean = true;\n public ignoreDuration: boolean = false;\n\n public constructor(context?: Omit) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n this.timestamp = startingTime;\n this.started = startingTime;\n if (context) {\n this.update(context);\n }\n }\n\n /** JSDoc */\n // eslint-disable-next-line complexity\n public update(context: SessionContext = {}): void {\n if (context.user) {\n if (!this.ipAddress && context.user.ip_address) {\n this.ipAddress = context.user.ip_address;\n }\n\n if (!this.did && !context.did) {\n this.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n this.timestamp = context.timestamp || timestampInSeconds();\n if (context.ignoreDuration) {\n this.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n this.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n this.init = context.init;\n }\n if (!this.did && context.did) {\n this.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n this.started = context.started;\n }\n if (this.ignoreDuration) {\n this.duration = undefined;\n } else if (typeof context.duration === 'number') {\n this.duration = context.duration;\n } else {\n const duration = this.timestamp - this.started;\n this.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n this.release = context.release;\n }\n if (context.environment) {\n this.environment = context.environment;\n }\n if (!this.ipAddress && context.ipAddress) {\n this.ipAddress = context.ipAddress;\n }\n if (!this.userAgent && context.userAgent) {\n this.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n this.errors = context.errors;\n }\n if (context.status) {\n this.status = context.status;\n }\n }\n\n /** JSDoc */\n public close(status?: Exclude): void {\n if (status) {\n this.update({ status });\n } else if (this.status === 'ok') {\n this.update({ status: 'exited' });\n } else {\n this.update();\n }\n }\n\n /** JSDoc */\n public toJSON(): {\n init: boolean;\n sid: string;\n did?: string;\n timestamp: string;\n started: string;\n duration?: number;\n status: SessionStatus;\n errors: number;\n attrs?: {\n release?: string;\n environment?: string;\n user_agent?: string;\n ip_address?: string;\n };\n } {\n return dropUndefinedKeys({\n sid: `${this.sid}`,\n init: this.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(this.started * 1000).toISOString(),\n timestamp: new Date(this.timestamp * 1000).toISOString(),\n status: this.status,\n errors: this.errors,\n did: typeof this.did === 'number' || typeof this.did === 'string' ? `${this.did}` : undefined,\n duration: this.duration,\n attrs: {\n release: this.release,\n environment: this.environment,\n ip_address: this.ipAddress,\n user_agent: this.userAgent,\n },\n });\n }\n}\n","/* eslint-disable max-lines */\nimport {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n SessionContext,\n Severity,\n Span,\n SpanContext,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { consoleSandbox, dateTimestampInSeconds, getGlobalObject, isNodeEnv, logger, uuid4 } from '@sentry/utils';\n\nimport { Scope } from './scope';\nimport { Session } from './session';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope?: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n hub?: Hub;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Hack to prevent bundlers from breaking our usage of the domain package in the cross-platform Hub package */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n domain?: { [key: string]: any };\n } & {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @hidden\n * @deprecated Can be removed once `Hub.getActiveDomain` is removed.\n */\nexport interface DomainAsCarrier extends Carrier {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: { [key: string]: any }[];\n}\n\n/**\n * @inheritDoc\n */\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[] = [{}];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {\n this.getStackTop().scope = scope;\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n public bindClient(client?: Client): void {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n public popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n public withScope(callback: (scope: Scope) => void): void {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n public getClient(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /** Returns the scope of the top stack. */\n public getScope(): Scope | undefined {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n let finalHint = hint;\n\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n let syntheticException: Error;\n try {\n throw new Error('Sentry syntheticException');\n } catch (exception) {\n syntheticException = exception as Error;\n }\n finalHint = {\n originalException: exception,\n syntheticException,\n };\n }\n\n this._invokeClient('captureException', exception, {\n ...finalHint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: Severity, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n let finalHint = hint;\n\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n let syntheticException: Error;\n try {\n throw new Error(message);\n } catch (exception) {\n syntheticException = exception as Error;\n }\n finalHint = {\n originalException: message,\n syntheticException,\n };\n }\n\n this._invokeClient('captureMessage', message, level, {\n ...finalHint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (event.type !== 'transaction') {\n this._lastEventId = eventId;\n }\n\n this._invokeClient('captureEvent', event, {\n ...hint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const { scope, client } = this.getStackTop();\n\n if (!scope || !client) return;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): void {\n const scope = this.getScope();\n if (scope) scope.setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n const scope = this.getScope();\n if (scope) scope.setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): void {\n const scope = this.getScope();\n if (scope) scope.setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): void {\n const scope = this.getScope();\n if (scope) scope.setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): void {\n const scope = this.getScope();\n if (scope) scope.setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n const scope = this.getScope();\n if (scope) scope.setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n public configureScope(callback: (scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (scope && client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startSpan(context: SpanContext): Span {\n return this._callExtensionMethod('startSpan', context);\n }\n\n /**\n * @inheritDoc\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n return this._callExtensionMethod('startTransaction', context, customSamplingContext);\n }\n\n /**\n * @inheritDoc\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n public endSession(): void {\n const layer = this.getStackTop();\n const scope = layer && layer.scope;\n const session = scope && scope.getSession();\n if (session) {\n session.close();\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n if (scope) {\n scope.setSession();\n }\n }\n\n /**\n * @inheritDoc\n */\n public startSession(context?: SessionContext): Session {\n const { scope, client } = this.getStackTop();\n const { release, environment } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const global = getGlobalObject<{ navigator?: { userAgent?: string } }>();\n const { userAgent } = global.navigator || {};\n\n const session = new Session({\n release,\n environment,\n ...(scope && { user: scope.getUser() }),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n if (scope) {\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n currentSession.update({ status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n }\n\n return session;\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n const { scope, client } = this.getStackTop();\n if (!scope) return;\n\n const session = scope.getSession && scope.getSession();\n if (session) {\n if (client && client.captureSession) {\n client.captureSession(session);\n }\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _invokeClient(method: M, ...args: any[]): void {\n const { scope, client } = this.getStackTop();\n if (client && client[method]) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (client as any)[method](...args, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n const carrier = getGlobalObject();\n carrier.__SENTRY__ = carrier.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return carrier;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Prefer domains over global if they are there (applicable only to Node environment)\n if (isNodeEnv()) {\n return getHubFromActiveDomain(registry);\n }\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * Returns the active domain, if one exists\n * @deprecated No longer used; remove in v7\n * @returns The domain, or undefined if there is no active domain\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveDomain(): DomainAsCarrier | undefined {\n logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.');\n\n const sentry = getMainCarrier().__SENTRY__;\n\n return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n}\n\n/**\n * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist\n * @returns discovered hub\n */\nfunction getHubFromActiveDomain(registry: Carrier): Hub {\n try {\n const sentry = getMainCarrier().__SENTRY__;\n const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n\n // If there's no active domain, just return global hub\n if (!activeDomain) {\n return getHubFromCarrier(registry);\n }\n\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {\n const registryHubTopStack = getHubFromCarrier(registry).getStackTop();\n setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));\n }\n\n // Return hub that lives on a domain\n return getHubFromCarrier(activeDomain);\n } catch (_Oo) {\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n }\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) return carrier.__SENTRY__.hub;\n carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n carrier.__SENTRY__.hub = new Hub();\n return carrier.__SENTRY__.hub;\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n carrier.__SENTRY__.hub = hub;\n return true;\n}\n","import { getCurrentHub, Hub, Scope } from '@sentry/hub';\nimport {\n Breadcrumb,\n CaptureContext,\n CustomSamplingContext,\n Event,\n Extra,\n Extras,\n Primitive,\n Severity,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\n\n/**\n * This calls a function on the current hub.\n * @param method function to call on hub.\n * @param args to pass to function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction callOnHub(method: string, ...args: any[]): T {\n const hub = getCurrentHub();\n if (hub && hub[method as keyof Hub]) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (hub[method as keyof Hub] as any)(...args);\n }\n throw new Error(`No hub defined or ${method} was not found on the hub, please open a bug report.`);\n}\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function captureException(exception: any, captureContext?: CaptureContext): string {\n let syntheticException: Error;\n try {\n throw new Error('Sentry syntheticException');\n } catch (exception) {\n syntheticException = exception as Error;\n }\n return callOnHub('captureException', exception, {\n captureContext,\n originalException: exception,\n syntheticException,\n });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nexport function captureMessage(message: string, captureContext?: CaptureContext | Severity): string {\n let syntheticException: Error;\n try {\n throw new Error(message);\n } catch (exception) {\n syntheticException = exception as Error;\n }\n\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n\n return callOnHub('captureMessage', message, level, {\n originalException: message,\n syntheticException,\n ...context,\n });\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nexport function captureEvent(event: Event): string {\n return callOnHub('captureEvent', event);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nexport function configureScope(callback: (scope: Scope) => void): void {\n callOnHub('configureScope', callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb): void {\n callOnHub('addBreadcrumb', breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): void {\n callOnHub('setContext', name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): void {\n callOnHub('setExtras', extras);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): void {\n callOnHub('setTags', tags);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): void {\n callOnHub('setExtra', key, extra);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): void {\n callOnHub('setTag', key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): void {\n callOnHub('setUser', user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nexport function withScope(callback: (scope: Scope) => void): void {\n callOnHub('withScope', callback);\n}\n\n/**\n * Calls a function on the latest client. Use this with caution, it's meant as\n * in \"internal\" helper so we don't need to expose every possible function in\n * the shim. It is not guaranteed that the client actually implements the\n * function.\n *\n * @param method The method to call on the client/client.\n * @param args Arguments to pass to the client/fontend.\n * @hidden\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _callOnClient(method: string, ...args: any[]): void {\n callOnHub('_invokeClient', method, ...args);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n return callOnHub('startTransaction', { ...context }, customSamplingContext);\n}\n","import { DsnComponents, DsnLike, SdkMetadata } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/**\n * Stores details about a Sentry SDK\n */\nexport interface APIDetails {\n /** The DSN as passed to Sentry.init() */\n initDsn: DsnLike;\n /** Metadata about the SDK (name, version, etc) for inclusion in envelope headers */\n metadata: SdkMetadata;\n /** The internally used Dsn object. */\n readonly dsn: DsnComponents;\n /** The envelope tunnel to use. */\n readonly tunnel?: string;\n}\n\n/**\n * Helper class to provide urls, headers and metadata that can be used to form\n * different types of requests to Sentry endpoints.\n * Supports both envelopes and regular event requests.\n *\n * @deprecated Please use APIDetails\n **/\nexport class API {\n /** The DSN as passed to Sentry.init() */\n public dsn: DsnLike;\n\n /** Metadata about the SDK (name, version, etc) for inclusion in envelope headers */\n public metadata: SdkMetadata;\n\n /** The internally used Dsn object. */\n private readonly _dsnObject: DsnComponents;\n\n /** The envelope tunnel to use. */\n private readonly _tunnel?: string;\n\n /** Create a new instance of API */\n public constructor(dsn: DsnLike, metadata: SdkMetadata = {}, tunnel?: string) {\n this.dsn = dsn;\n this._dsnObject = makeDsn(dsn);\n this.metadata = metadata;\n this._tunnel = tunnel;\n }\n\n /** Returns the Dsn object. */\n public getDsn(): DsnComponents {\n return this._dsnObject;\n }\n\n /** Does this transport force envelopes? */\n public forceEnvelope(): boolean {\n return !!this._tunnel;\n }\n\n /** Returns the prefix to construct Sentry ingestion API endpoints. */\n public getBaseApiEndpoint(): string {\n return getBaseApiEndpoint(this._dsnObject);\n }\n\n /** Returns the store endpoint URL. */\n public getStoreEndpoint(): string {\n return getStoreEndpoint(this._dsnObject);\n }\n\n /**\n * Returns the store endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n public getStoreEndpointWithUrlEncodedAuth(): string {\n return getStoreEndpointWithUrlEncodedAuth(this._dsnObject);\n }\n\n /**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n public getEnvelopeEndpointWithUrlEncodedAuth(): string {\n return getEnvelopeEndpointWithUrlEncodedAuth(this._dsnObject, this._tunnel);\n }\n}\n\n/** Initializes API Details */\nexport function initAPIDetails(dsn: DsnLike, metadata?: SdkMetadata, tunnel?: string): APIDetails {\n return {\n initDsn: dsn,\n metadata: metadata || {},\n dsn: makeDsn(dsn),\n tunnel,\n } as APIDetails;\n}\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents, target: 'store' | 'envelope'): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/${target}/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n });\n}\n\n/** Returns the store endpoint URL. */\nfunction getStoreEndpoint(dsn: DsnComponents): string {\n return _getIngestEndpoint(dsn, 'store');\n}\n\n/**\n * Returns the store endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getStoreEndpointWithUrlEncodedAuth(dsn: DsnComponents): string {\n return `${getStoreEndpoint(dsn)}?${_encodedAuth(dsn)}`;\n}\n\n/** Returns the envelope endpoint URL. */\nfunction _getEnvelopeEndpoint(dsn: DsnComponents): string {\n return _getIngestEndpoint(dsn, 'envelope');\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(dsn: DsnComponents, tunnel?: string): string {\n return tunnel ? tunnel : `${_getEnvelopeEndpoint(dsn)}?${_encodedAuth(dsn)}`;\n}\n\n/**\n * Returns an object that can be used in request headers.\n * This is needed for node and the old /store endpoint in sentry\n */\nexport function getRequestHeaders(\n dsn: DsnComponents,\n clientName: string,\n clientVersion: string,\n): { [key: string]: string } {\n // CHANGE THIS to use metadata but keep clientName and clientVersion compatible\n const header = [`Sentry sentry_version=${SENTRY_API_VERSION}`];\n header.push(`sentry_client=${clientName}/${clientVersion}`);\n header.push(`sentry_key=${dsn.publicKey}`);\n if (dsn.pass) {\n header.push(`sentry_secret=${dsn.pass}`);\n }\n return {\n 'Content-Type': 'application/json',\n 'X-Sentry-Auth': header.join(', '),\n };\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n if (!dialogOptions.user) {\n continue;\n }\n if (dialogOptions.user.name) {\n encodedOptions += `&name=${encodeURIComponent(dialogOptions.user.name)}`;\n }\n if (dialogOptions.user.email) {\n encodedOptions += `&email=${encodeURIComponent(dialogOptions.user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Integration, Options } from '@sentry/types';\nimport { addNonEnumerableProperty, logger } from '@sentry/utils';\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n} & { initialized?: boolean };\n\n/**\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n return integrations.reduce((acc, integrations) => {\n if (acc.every(accIntegration => integrations.name !== accIntegration.name)) {\n acc.push(integrations);\n }\n return acc;\n }, [] as Integration[]);\n}\n\n/** Gets integration to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = (options.defaultIntegrations && [...options.defaultIntegrations]) || [];\n const userIntegrations = options.integrations;\n\n let integrations: Integration[] = [...filterDuplicates(defaultIntegrations)];\n\n if (Array.isArray(userIntegrations)) {\n // Filter out integrations that are also included in user options\n integrations = [\n ...integrations.filter(integrations =>\n userIntegrations.every(userIntegration => userIntegration.name !== integrations.name),\n ),\n // And filter out duplicated user options integrations\n ...filterDuplicates(userIntegrations),\n ];\n } else if (typeof userIntegrations === 'function') {\n integrations = userIntegrations(integrations);\n integrations = Array.isArray(integrations) ? integrations : [integrations];\n }\n\n // Make sure that if present, `Debug` integration will always run last\n const integrationsNames = integrations.map(i => i.name);\n const alwaysLastToRun = 'Debug';\n if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {\n integrations.push(...integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1));\n }\n\n return integrations;\n}\n\n/** Setup given integration */\nexport function setupIntegration(integration: Integration): void {\n if (installedIntegrations.indexOf(integration.name) !== -1) {\n return;\n }\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n logger.log(`Integration installed: ${integration.name}`);\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(options: O): IntegrationIndex {\n const integrations: IntegrationIndex = {};\n getIntegrationsToSetup(options).forEach(integration => {\n integrations[integration.name] = integration;\n setupIntegration(integration);\n });\n // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty`\n // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be\n // considered a member of the index the way the actual integrations are\n addNonEnumerableProperty(integrations, 'initialized', true);\n return integrations;\n}\n","/* eslint-disable max-lines */\nimport { Scope, Session } from '@sentry/hub';\nimport {\n Client,\n DsnComponents,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n Options,\n Severity,\n Transport,\n} from '@sentry/types';\nimport {\n checkOrSetAlreadyCaught,\n dateTimestampInSeconds,\n isDebugBuild,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n normalize,\n rejectedSyncPromise,\n resolvedSyncPromise,\n SentryError,\n SyncPromise,\n truncate,\n uuid4,\n} from '@sentry/utils';\n\nimport { Backend, BackendClass } from './basebackend';\nimport { IntegrationIndex, setupIntegrations } from './integration';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding backend constructor and options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}. Also, the Backend instance is available via\n * {@link Client.getBackend}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event via the backend, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(NodeBackend, options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /**\n * The backend used to physically interact in the environment. Usually, this\n * will correspond to the client. When composing SDKs, however, the Backend\n * from the root SDK will be used.\n */\n protected readonly _backend: B;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n /** Array of used integrations. */\n protected _integrations: IntegrationIndex = {};\n\n /** Number of calls being processed */\n protected _numProcessing: number = 0;\n\n /**\n * Initializes this client instance.\n *\n * @param backendClass A constructor function to create the backend.\n * @param options Options for the client.\n */\n protected constructor(backendClass: BackendClass, options: O) {\n this._backend = new backendClass(options);\n this._options = options;\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._getBackend()\n .eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: Severity, hint?: EventHint, scope?: Scope): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this._getBackend().eventFromMessage(String(message), level, hint)\n : this._getBackend().eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n if (isDebugBuild()) {\n logger.warn('SDK not enabled, will not capture session.');\n }\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n if (isDebugBuild()) {\n logger.warn('Discarded session because of missing or non-string release');\n }\n } else {\n this._sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n session.update({ init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport {\n return this._getBackend().getTransport();\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return this.getTransport()\n .close(timeout)\n .then(transportFlushed => clientFinished && transportFlushed);\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrations.initialized) {\n this._integrations = setupIntegrations(this._options);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n session.update({\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /** Deliver captured session to Sentry */\n protected _sendSession(session: Session): void {\n this._getBackend().sendSession(session);\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Returns the current backend. */\n protected _getBackend(): B {\n return this._backend;\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike {\n const { normalizeDepth = 3 } = this.getOptions();\n const prepared: Event = {\n ...event,\n event_id: event.event_id || (hint && hint.event_id ? hint.event_id : uuid4()),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n\n this._applyClientOptions(prepared);\n this._applyIntegrationsMetadata(prepared);\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint && hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n if (finalScope) {\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (evt) {\n // TODO this is more of the hack trying to solve https://github.com/getsentry/sentry-javascript/issues/2809\n // it is only attached as extra data to the event if the event somehow skips being normalized\n evt.sdkProcessingMetadata = { ...evt.sdkProcessingMetadata, normalizeDepth: normalize(normalizeDepth) };\n }\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return this._normalizeEvent(evt, normalizeDepth);\n }\n return evt;\n });\n }\n\n /**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\n protected _normalizeEvent(event: Event | null, depth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth),\n }),\n };\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n normalized.contexts.trace = event.contexts.trace;\n }\n\n event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, baseClientNormalized: true };\n\n return normalized;\n }\n\n /**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\n protected _applyClientOptions(event: Event): void {\n const options = this.getOptions();\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : 'production';\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n }\n\n /**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\n protected _applyIntegrationsMetadata(event: Event): void {\n const integrationsArray = Object.keys(this._integrations);\n if (integrationsArray.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray];\n }\n }\n\n /**\n * Tells the backend to send this event\n * @param event The Sentry event to send\n */\n protected _sendEvent(event: Event): void {\n this._getBackend().sendEvent(event);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n logger.error(reason);\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeSend, sampleRate } = this.getOptions();\n const transport = this.getTransport();\n\n type RecordLostEvent = NonNullable;\n type RecordLostEventParams = Parameters;\n\n function recordLostEvent(outcome: RecordLostEventParams[0], category: RecordLostEventParams[1]): void {\n if (transport.recordLostEvent) {\n transport.recordLostEvent(outcome, category);\n }\n }\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.'));\n }\n\n const isTransaction = event.type === 'transaction';\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n recordLostEvent('sample_rate', 'event');\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n ),\n );\n }\n\n return this._prepareEvent(event, scope, hint)\n .then(prepared => {\n if (prepared === null) {\n recordLostEvent('event_processor', event.type || 'event');\n throw new SentryError('An event processor returned null, will not send event.');\n }\n\n const isInternalException = hint && hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException || isTransaction || !beforeSend) {\n return prepared;\n }\n\n const beforeSendResult = beforeSend(prepared, hint);\n return _ensureBeforeSendRv(beforeSendResult);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n recordLostEvent('before_send', event.type || 'event');\n throw new SentryError('`beforeSend` returned `null`, will not send event.');\n }\n\n const session = scope && scope.getSession && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n this._sendEvent(processedEvent);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason as Error,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing += 1;\n void promise.then(\n value => {\n this._numProcessing -= 1;\n return value;\n },\n reason => {\n this._numProcessing -= 1;\n return reason;\n },\n );\n }\n}\n\n/**\n * Verifies that return value of configured `beforeSend` is of expected type.\n */\nfunction _ensureBeforeSendRv(rv: PromiseLike | Event | null): PromiseLike | Event | null {\n const nullErr = '`beforeSend` method has to return `null` or a valid event.';\n if (isThenable(rv)) {\n return rv.then(\n event => {\n if (!(isPlainObject(event) || event === null)) {\n throw new SentryError(nullErr);\n }\n return event;\n },\n e => {\n throw new SentryError(`beforeSend rejected with ${e}`);\n },\n );\n } else if (!(isPlainObject(rv) || rv === null)) {\n throw new SentryError(nullErr);\n }\n return rv;\n}\n","import { Event, Response, Transport } from '@sentry/types';\nimport { resolvedSyncPromise } from '@sentry/utils';\n\n/** Noop transport */\nexport class NoopTransport implements Transport {\n /**\n * @inheritDoc\n */\n public sendEvent(_: Event): PromiseLike {\n return resolvedSyncPromise({\n reason: `NoopTransport: Event has been skipped because no Dsn is configured.`,\n status: 'skipped',\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(_?: number): PromiseLike {\n return resolvedSyncPromise(true);\n }\n}\n","import { Event, EventHint, Options, Session, Severity, Transport } from '@sentry/types';\nimport { isDebugBuild, logger, SentryError } from '@sentry/utils';\n\nimport { NoopTransport } from './transports/noop';\n\n/**\n * Internal platform-dependent Sentry SDK Backend.\n *\n * While {@link Client} contains business logic specific to an SDK, the\n * Backend offers platform specific implementations for low-level operations.\n * These are persisting and loading information, sending events, and hooking\n * into the environment.\n *\n * Backends receive a handle to the Client in their constructor. When a\n * Backend automatically generates events, it must pass them to\n * the Client for validation and processing first.\n *\n * Usually, the Client will be of corresponding type, e.g. NodeBackend\n * receives NodeClient. However, higher-level SDKs can choose to instantiate\n * multiple Backends and delegate tasks between them. In this case, an event\n * generated by one backend might very well be sent by another one.\n *\n * The client also provides access to options via {@link Client.getOptions}.\n * @hidden\n */\nexport interface Backend {\n /** Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n eventFromException(exception: any, hint?: EventHint): PromiseLike;\n\n /** Creates an {@link Event} from primitive inputs to `captureMessage`. */\n eventFromMessage(message: string, level?: Severity, hint?: EventHint): PromiseLike;\n\n /** Submits the event to Sentry */\n sendEvent(event: Event): void;\n\n /** Submits the session to Sentry */\n sendSession(session: Session): void;\n\n /**\n * Returns the transport that is used by the backend.\n * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n *\n * @returns The transport.\n */\n getTransport(): Transport;\n}\n\n/**\n * A class object that can instantiate Backend objects.\n * @hidden\n */\nexport type BackendClass = new (options: O) => B;\n\n/**\n * This is the base implemention of a Backend.\n * @hidden\n */\nexport abstract class BaseBackend implements Backend {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** Cached transport used internally. */\n protected _transport: Transport;\n\n /** Creates a new backend instance. */\n public constructor(options: O) {\n this._options = options;\n if (!this._options.dsn) {\n logger.warn('No DSN provided, backend will not do anything.');\n }\n this._transport = this._setupTransport();\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public eventFromException(_exception: any, _hint?: EventHint): PromiseLike {\n throw new SentryError('Backend has to implement `eventFromException` method');\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(_message: string, _level?: Severity, _hint?: EventHint): PromiseLike {\n throw new SentryError('Backend has to implement `eventFromMessage` method');\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): void {\n void this._transport.sendEvent(event).then(null, reason => {\n if (isDebugBuild()) {\n logger.error(`Error while sending event: ${reason}`);\n }\n });\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session): void {\n if (!this._transport.sendSession) {\n if (isDebugBuild()) {\n logger.warn(\"Dropping session because custom transport doesn't implement sendSession\");\n }\n return;\n }\n\n void this._transport.sendSession(session).then(null, reason => {\n if (isDebugBuild()) {\n logger.error(`Error while sending session: ${reason}`);\n }\n });\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport {\n return this._transport;\n }\n\n /**\n * Sets up the transport so it can be used later to send requests.\n */\n protected _setupTransport(): Transport {\n return new NoopTransport();\n }\n}\n","import { Event, SdkInfo, SentryRequest, SentryRequestType, Session, SessionAggregates } from '@sentry/types';\nimport { dsnToString, normalize } from '@sentry/utils';\n\nimport { APIDetails, getEnvelopeEndpointWithUrlEncodedAuth, getStoreEndpointWithUrlEncodedAuth } from './api';\n\n/** Extract sdk info from from the API metadata */\nfunction getSdkMetadataForEnvelopeHeader(api: APIDetails): SdkInfo | undefined {\n if (!api.metadata || !api.metadata.sdk) {\n return;\n }\n const { name, version } = api.metadata.sdk;\n return { name, version };\n}\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event: Event, sdkInfo?: SdkInfo): Event {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates a SentryRequest from a Session. */\nexport function sessionToSentryRequest(session: Session | SessionAggregates, api: APIDetails): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const envelopeHeaders = JSON.stringify({\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!api.tunnel && { dsn: dsnToString(api.dsn) }),\n });\n // I know this is hacky but we don't want to add `session` to request type since it's never rate limited\n const type: SentryRequestType = 'aggregates' in session ? ('sessions' as SentryRequestType) : 'session';\n const itemHeaders = JSON.stringify({\n type,\n });\n\n return {\n body: `${envelopeHeaders}\\n${itemHeaders}\\n${JSON.stringify(session)}`,\n type,\n url: getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel),\n };\n}\n\n/** Creates a SentryRequest from an event. */\nexport function eventToSentryRequest(event: Event, api: APIDetails): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const eventType = event.type || 'event';\n const useEnvelope = eventType === 'transaction' || !!api.tunnel;\n\n const { transactionSampling } = event.sdkProcessingMetadata || {};\n const { method: samplingMethod, rate: sampleRate } = transactionSampling || {};\n\n // TODO: Below is a temporary hack in order to debug a serialization error - see\n // https://github.com/getsentry/sentry-javascript/issues/2809,\n // https://github.com/getsentry/sentry-javascript/pull/4425, and\n // https://github.com/getsentry/sentry-javascript/pull/4574.\n //\n // TL; DR: even though we normalize all events (which should prevent this), something is causing `JSON.stringify` to\n // throw a circular reference error.\n //\n // When it's time to remove it:\n // 1. Delete everything between here and where the request object `req` is created, EXCEPT the line deleting\n // `sdkProcessingMetadata`\n // 2. Restore the original version of the request body, which is commented out\n // 3. Search for either of the PR URLs above and pull out the companion hacks in the browser playwright tests and the\n // baseClient tests in this package\n enhanceEventWithSdkInfo(event, api.metadata.sdk);\n event.tags = event.tags || {};\n event.extra = event.extra || {};\n\n // In theory, all events should be marked as having gone through normalization and so\n // we should never set this tag/extra data\n if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) {\n event.tags.skippedNormalization = true;\n event.extra.normalizeDepth = event.sdkProcessingMetadata ? event.sdkProcessingMetadata.normalizeDepth : 'unset';\n }\n\n // prevent this data from being sent to sentry\n // TODO: This is NOT part of the hack - DO NOT DELETE\n delete event.sdkProcessingMetadata;\n\n let body;\n try {\n // 99.9% of events should get through just fine - no change in behavior for them\n body = JSON.stringify(event);\n } catch (err) {\n // Record data about the error without replacing original event data, then force renormalization\n event.tags.JSONStringifyError = true;\n event.extra.JSONStringifyError = err;\n try {\n body = JSON.stringify(normalize(event));\n } catch (newErr) {\n // At this point even renormalization hasn't worked, meaning something about the event data has gone very wrong.\n // Time to cut our losses and record only the new error. With luck, even in the problematic cases we're trying to\n // debug with this hack, we won't ever land here.\n const innerErr = newErr as Error;\n body = JSON.stringify({\n message: 'JSON.stringify error after renormalization',\n // setting `extra: { innerErr }` here for some reason results in an empty object, so unpack manually\n extra: { message: innerErr.message, stack: innerErr.stack },\n });\n }\n }\n\n const req: SentryRequest = {\n // this is the relevant line of code before the hack was added, to make it easy to undo said hack once we've solved\n // the mystery\n // body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),\n body,\n type: eventType,\n url: useEnvelope\n ? getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel)\n : getStoreEndpointWithUrlEncodedAuth(api.dsn),\n };\n\n // https://develop.sentry.dev/sdk/envelopes/\n\n // Since we don't need to manipulate envelopes nor store them, there is no\n // exported concept of an Envelope with operations including serialization and\n // deserialization. Instead, we only implement a minimal subset of the spec to\n // serialize events inline here.\n if (useEnvelope) {\n const envelopeHeaders = JSON.stringify({\n event_id: event.event_id,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!api.tunnel && { dsn: dsnToString(api.dsn) }),\n });\n const itemHeaders = JSON.stringify({\n type: eventType,\n\n // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and\n // explicitly-set sampling decisions). Are we good with that?\n sample_rates: [{ id: samplingMethod, rate: sampleRate }],\n\n // The content-type is assumed to be 'application/json' and not part of\n // the current spec for transaction items, so we don't bloat the request\n // body with it.\n //\n // content_type: 'application/json',\n //\n // The length is optional. It must be the number of bytes in req.Body\n // encoded as UTF-8. Since the server can figure this out and would\n // otherwise refuse events that report the length incorrectly, we decided\n // not to send the length to avoid problems related to reporting the wrong\n // size and to reduce request body size.\n //\n // length: new TextEncoder().encode(req.body).length,\n });\n // The trailing newline is optional. We intentionally don't send it to avoid\n // sending unnecessary bytes.\n //\n // const envelope = `${envelopeHeaders}\\n${itemHeaders}\\n${req.body}\\n`;\n const envelope = `${envelopeHeaders}\\n${itemHeaders}\\n${req.body}`;\n req.body = envelope;\n }\n\n return req;\n}\n","import { Integration, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string = FunctionToString.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n }\n}\n","export const SDK_VERSION = '6.18.1';\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Event, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, isDebugBuild, isMatchingPattern, logger } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\n/** JSDoc */\ninterface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreInternal: boolean;\n\n /** @deprecated use {@link InboundFiltersOptions.allowUrls} instead. */\n whitelistUrls: Array;\n /** @deprecated use {@link InboundFiltersOptions.denyUrls} instead. */\n blacklistUrls: Array;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string = InboundFilters.id;\n\n public constructor(private readonly _options: Partial = {}) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n const hub = getCurrentHub();\n if (!hub) {\n return event;\n }\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n // This checks prevents most of the occurrences of the bug linked below:\n // https://github.com/getsentry/sentry-javascript/issues/2622\n // The bug is caused by multiple SDK instances, where one is minified and one is using non-mangled code.\n // Unfortunatelly we cannot fix it reliably (thus reserved property in rollup's terser config),\n // as we cannot force people using multiple instances in their apps to sync SDK versions.\n const options = typeof self._mergeOptions === 'function' ? self._mergeOptions(clientOptions) : {};\n if (typeof self._shouldDropEvent !== 'function') {\n return event;\n }\n return self._shouldDropEvent(event, options) ? null : event;\n }\n return event;\n });\n }\n\n /** JSDoc */\n private _shouldDropEvent(event: Event, options: Partial): boolean {\n if (this._isSentryError(event, options)) {\n if (isDebugBuild()) {\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n }\n return true;\n }\n if (this._isIgnoredError(event, options)) {\n if (isDebugBuild()) {\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n }\n return true;\n }\n if (this._isDeniedUrl(event, options)) {\n if (isDebugBuild()) {\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${this._getEventFilterUrl(event)}`,\n );\n }\n return true;\n }\n if (!this._isAllowedUrl(event, options)) {\n if (isDebugBuild()) {\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${this._getEventFilterUrl(event)}`,\n );\n }\n return true;\n }\n return false;\n }\n\n /** JSDoc */\n private _isSentryError(event: Event, options: Partial): boolean {\n if (!options.ignoreInternal) {\n return false;\n }\n\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n\n return false;\n }\n\n /** JSDoc */\n private _isIgnoredError(event: Event, options: Partial): boolean {\n if (!options.ignoreErrors || !options.ignoreErrors.length) {\n return false;\n }\n\n return this._getPossibleEventMessages(event).some(message =>\n // Not sure why TypeScript complains here...\n (options.ignoreErrors as Array).some(pattern => isMatchingPattern(message, pattern)),\n );\n }\n\n /** JSDoc */\n private _isDeniedUrl(event: Event, options: Partial): boolean {\n // TODO: Use Glob instead?\n if (!options.denyUrls || !options.denyUrls.length) {\n return false;\n }\n const url = this._getEventFilterUrl(event);\n return !url ? false : options.denyUrls.some(pattern => isMatchingPattern(url, pattern));\n }\n\n /** JSDoc */\n private _isAllowedUrl(event: Event, options: Partial): boolean {\n // TODO: Use Glob instead?\n if (!options.allowUrls || !options.allowUrls.length) {\n return true;\n }\n const url = this._getEventFilterUrl(event);\n return !url ? true : options.allowUrls.some(pattern => isMatchingPattern(url, pattern));\n }\n\n /** JSDoc */\n private _mergeOptions(clientOptions: Partial = {}): Partial {\n return {\n allowUrls: [\n // eslint-disable-next-line deprecation/deprecation\n ...(this._options.whitelistUrls || []),\n ...(this._options.allowUrls || []),\n // eslint-disable-next-line deprecation/deprecation\n ...(clientOptions.whitelistUrls || []),\n ...(clientOptions.allowUrls || []),\n ],\n denyUrls: [\n // eslint-disable-next-line deprecation/deprecation\n ...(this._options.blacklistUrls || []),\n ...(this._options.denyUrls || []),\n // eslint-disable-next-line deprecation/deprecation\n ...(clientOptions.blacklistUrls || []),\n ...(clientOptions.denyUrls || []),\n ],\n ignoreErrors: [\n ...(this._options.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...DEFAULT_IGNORE_ERRORS,\n ],\n ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true,\n };\n }\n\n /** JSDoc */\n private _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n try {\n const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n if (isDebugBuild()) {\n logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n }\n return [];\n }\n }\n return [];\n }\n\n /** JSDoc */\n private _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n }\n\n /** JSDoc */\n private _getEventFilterUrl(event: Event): string | null {\n try {\n if (event.stacktrace) {\n return this._getLastValidUrl(event.stacktrace.frames);\n }\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? this._getLastValidUrl(frames) : null;\n } catch (oO) {\n if (isDebugBuild()) {\n logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n }\n return null;\n }\n }\n}\n","import { StackFrame } from '@sentry/types';\nimport { StackLineParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n // All browser frames are considered in_app\n in_app: true,\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.*?) ?\\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack||[-a-z]+:|.*bundle|\\/).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nexport const chrome: StackLineParser = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nexport const gecko: StackLineParser = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || `eval`;\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nconst winjsRegex =\n /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nexport const winjs: StackLineParser = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nexport const opera10: StackLineParser = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nexport const opera11: StackLineParser = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { Event, Exception, StackFrame } from '@sentry/types';\nimport { createStackParser, extractExceptionKeysForMessage, isEvent, normalizeToSize } from '@sentry/utils';\n\nimport { chrome, gecko, opera10, opera11, winjs } from './stack-parsers';\n\n/**\n * This function creates an exception from an TraceKitStackTrace\n * @param stacktrace TraceKitStackTrace that will be converted to an exception\n * @hidden\n */\nexport function exceptionFromError(ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames && frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n exception: Record,\n syntheticException?: Error,\n rejection?: boolean,\n): Event {\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : rejection ? 'UnhandledRejection' : 'Error',\n value: `Non-Error ${\n rejection ? 'promise rejection' : 'exception'\n } captured with keys: ${extractExceptionKeysForMessage(exception)}`,\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(syntheticException);\n if (frames.length) {\n event.stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(ex: Error & { framesToPop?: number; stacktrace?: string }): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n // The order of the parsers in important\n return createStackParser(opera10, opera11, chrome, winjs, gecko)(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractMessage(ex: any): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n","import { Event, EventHint, Options, Severity } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isPlainObject,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport { eventFromError, eventFromPlainObject, parseStackFrames } from './parsers';\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(options: Options, exception: unknown, hint?: EventHint): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(exception, syntheticException, {\n attachStacktrace: options.attachStacktrace,\n });\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = Severity.Error;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n options: Options,\n message: string,\n level: Severity = Severity.Info,\n hint?: EventHint,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(message, syntheticException, {\n attachStacktrace: options.attachStacktrace,\n });\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n exception: unknown,\n syntheticException?: Error,\n options: {\n isRejection?: boolean;\n attachStacktrace?: boolean;\n } = {},\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception as DOMError) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(message, syntheticException, options);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception as Error)) {\n // we have a real Error object, do nothing\n return eventFromError(exception as Error);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(objectException, syntheticException, options.isRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(exception as string, syntheticException, options);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n input: string,\n syntheticException?: Error,\n options: {\n attachStacktrace?: boolean;\n } = {},\n): Event {\n const event: Event = {\n message: input,\n };\n\n if (options.attachStacktrace && syntheticException) {\n const frames = parseStackFrames(syntheticException);\n if (frames.length) {\n event.stacktrace = { frames };\n }\n }\n\n return event;\n}\n","import { forget, getGlobalObject, isDebugBuild, isNativeFetch, logger, supportsFetch } from '@sentry/utils';\n\nconst global = getGlobalObject();\nlet cachedFetchImpl: FetchImpl;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(global.fetch)) {\n return (cachedFetchImpl = global.fetch.bind(global));\n }\n\n const document = global.document;\n let fetchImpl = global.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === `function`) {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n if (isDebugBuild()) {\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(global));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/**\n * Sends sdk client report using sendBeacon or fetch as a fallback if available\n *\n * @param url report endpoint\n * @param body report payload\n */\nexport function sendReport(url: string, body: string): void {\n const isRealNavigator = Object.prototype.toString.call(global && global.navigator) === '[object Navigator]';\n const hasSendBeacon = isRealNavigator && typeof global.navigator.sendBeacon === 'function';\n\n if (hasSendBeacon) {\n // Prevent illegal invocations - https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch\n const sendBeacon = global.navigator.sendBeacon.bind(global.navigator);\n return sendBeacon(url, body);\n }\n\n if (supportsFetch()) {\n const fetch = getNativeFetchImplementation();\n return forget(\n fetch(url, {\n body,\n method: 'POST',\n credentials: 'omit',\n keepalive: true,\n }),\n );\n }\n}\n","/**\n * Consumes the promise and logs the error when it rejects.\n * @param promise A promise to forget.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function forget(promise: PromiseLike): void {\n void promise.then(null, e => {\n // TODO: Use a better logging mechanism\n // eslint-disable-next-line no-console\n console.error(e);\n });\n}\n","import {\n APIDetails,\n eventToSentryRequest,\n getEnvelopeEndpointWithUrlEncodedAuth,\n getStoreEndpointWithUrlEncodedAuth,\n initAPIDetails,\n sessionToSentryRequest,\n} from '@sentry/core';\nimport {\n ClientReport,\n Event,\n Outcome,\n Response as SentryResponse,\n SentryRequest,\n SentryRequestType,\n Session,\n Transport,\n TransportOptions,\n} from '@sentry/types';\nimport {\n createClientReportEnvelope,\n dsnToString,\n eventStatusFromHttpCode,\n getGlobalObject,\n isDebugBuild,\n logger,\n makePromiseBuffer,\n parseRetryAfterHeader,\n PromiseBuffer,\n serializeEnvelope,\n} from '@sentry/utils';\n\nimport { sendReport } from './utils';\n\nfunction requestTypeToCategory(ty: SentryRequestType): string {\n const tyStr = ty as string;\n return tyStr === 'event' ? 'error' : tyStr;\n}\n\nconst global = getGlobalObject();\n\n/** Base Transport class implementation */\nexport abstract class BaseTransport implements Transport {\n /**\n * @deprecated\n */\n public url: string;\n\n /** Helper to get Sentry API endpoints. */\n protected readonly _api: APIDetails;\n\n /** A simple buffer holding all requests. */\n protected readonly _buffer: PromiseBuffer = makePromiseBuffer(30);\n\n /** Locks transport after receiving rate limits in a response */\n protected readonly _rateLimits: Record = {};\n\n protected _outcomes: { [key: string]: number } = {};\n\n public constructor(public options: TransportOptions) {\n this._api = initAPIDetails(options.dsn, options._metadata, options.tunnel);\n // eslint-disable-next-line deprecation/deprecation\n this.url = getStoreEndpointWithUrlEncodedAuth(this._api.dsn);\n\n if (this.options.sendClientReports && global.document) {\n global.document.addEventListener('visibilitychange', () => {\n if (global.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): PromiseLike {\n return this._sendRequest(eventToSentryRequest(event, this._api), event);\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session): PromiseLike {\n return this._sendRequest(sessionToSentryRequest(session, this._api), session);\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this._buffer.drain(timeout);\n }\n\n /**\n * @inheritDoc\n */\n public recordLostEvent(reason: Outcome, category: SentryRequestType): void {\n if (!this.options.sendClientReports) {\n return;\n }\n // We want to track each category (event, transaction, session) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n const key = `${requestTypeToCategory(category)}:${reason}`;\n logger.log(`Adding outcome: ${key}`);\n this._outcomes[key] = (this._outcomes[key] ?? 0) + 1;\n }\n\n /**\n * Send outcomes as an envelope\n */\n protected _flushOutcomes(): void {\n if (!this.options.sendClientReports) {\n return;\n }\n\n const outcomes = this._outcomes;\n this._outcomes = {};\n\n // Nothing to send\n if (!Object.keys(outcomes).length) {\n logger.log('No outcomes to flush');\n return;\n }\n\n logger.log(`Flushing outcomes:\\n${JSON.stringify(outcomes, null, 2)}`);\n\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._api.dsn, this._api.tunnel);\n\n const discardedEvents = Object.keys(outcomes).map(key => {\n const [category, reason] = key.split(':');\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n // TODO: Improve types on discarded_events to get rid of cast\n }) as ClientReport['discarded_events'];\n const envelope = createClientReportEnvelope(discardedEvents, this._api.tunnel && dsnToString(this._api.dsn));\n\n try {\n sendReport(url, serializeEnvelope(envelope));\n } catch (e) {\n logger.error(e);\n }\n }\n\n /**\n * Handle Sentry repsonse for promise-based transports.\n */\n protected _handleResponse({\n requestType,\n response,\n headers,\n resolve,\n reject,\n }: {\n requestType: SentryRequestType;\n response: Response | XMLHttpRequest;\n headers: Record;\n resolve: (value?: SentryResponse | PromiseLike | null | undefined) => void;\n reject: (reason?: unknown) => void;\n }): void {\n const status = eventStatusFromHttpCode(response.status);\n /**\n * \"The name is case-insensitive.\"\n * https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n */\n const limited = this._handleRateLimit(headers);\n if (limited && isDebugBuild()) {\n logger.warn(`Too many ${requestType} requests, backing off until: ${this._disabledUntil(requestType)}`);\n }\n\n if (status === 'success') {\n resolve({ status });\n return;\n }\n\n reject(response);\n }\n\n /**\n * Gets the time that given category is disabled until for rate limiting\n */\n protected _disabledUntil(requestType: SentryRequestType): Date {\n const category = requestTypeToCategory(requestType);\n return this._rateLimits[category] || this._rateLimits.all;\n }\n\n /**\n * Checks if a category is rate limited\n */\n protected _isRateLimited(requestType: SentryRequestType): boolean {\n return this._disabledUntil(requestType) > new Date(Date.now());\n }\n\n /**\n * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header.\n */\n protected _handleRateLimit(headers: Record): boolean {\n const now = Date.now();\n const rlHeader = headers['x-sentry-rate-limits'];\n const raHeader = headers['retry-after'];\n\n if (rlHeader) {\n // rate limit headers are of the form\n //
,
,..\n // where each
is of the form\n // : : : \n // where\n // is a delay in ms\n // is the event type(s) (error, transaction, etc) being rate limited and is of the form\n // ;;...\n // is what's being limited (org, project, or key) - ignored by SDK\n // is an arbitrary string like \"org_quota\" - ignored by SDK\n for (const limit of rlHeader.trim().split(',')) {\n const parameters = limit.split(':', 2);\n const headerDelay = parseInt(parameters[0], 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n for (const category of parameters[1].split(';')) {\n this._rateLimits[category || 'all'] = new Date(now + delay);\n }\n }\n return true;\n } else if (raHeader) {\n this._rateLimits.all = new Date(now + parseRetryAfterHeader(now, raHeader));\n return true;\n }\n return false;\n }\n\n protected abstract _sendRequest(\n sentryRequest: SentryRequest,\n originalPayload: Event | Session,\n ): PromiseLike;\n}\n","import { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import { Envelope } from '@sentry/types';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as E;\n}\n\n/**\n * Serializes an envelope into a string.\n */\nexport function serializeEnvelope(envelope: Envelope): string {\n const [headers, items] = envelope;\n const serializedHeaders = JSON.stringify(headers);\n\n // Have to cast items to any here since Envelope is a union type\n // Fixed in Typescript 4.2\n // TODO: Remove any[] cast when we upgrade to TS 4.2\n // https://github.com/microsoft/TypeScript/issues/36390\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (items as any[]).reduce((acc, item: typeof items[number]) => {\n const [itemHeaders, payload] = item;\n return `${acc}\\n${JSON.stringify(itemHeaders)}\\n${JSON.stringify(payload)}`;\n }, serializedHeaders);\n}\n","import { EventStatus } from '@sentry/types';\n/**\n * Converts an HTTP status code to sentry status {@link EventStatus}.\n *\n * @param code number HTTP status code\n * @returns EventStatus\n */\nexport function eventStatusFromHttpCode(code: number): EventStatus {\n if (code >= 200 && code < 300) {\n return 'success';\n }\n\n if (code === 429) {\n return 'rate_limit';\n }\n\n if (code >= 400 && code < 500) {\n return 'invalid';\n }\n\n if (code >= 500) {\n return 'failed';\n }\n\n return 'unknown';\n}\n","import { Event, Response, SentryRequest, Session, TransportOptions } from '@sentry/types';\nimport { SentryError, supportsReferrerPolicy, SyncPromise } from '@sentry/utils';\n\nimport { BaseTransport } from './base';\nimport { FetchImpl, getNativeFetchImplementation } from './utils';\n\n/** `fetch` based transport */\nexport class FetchTransport extends BaseTransport {\n /**\n * Fetch API reference which always points to native browser implementation.\n */\n private _fetch: typeof fetch;\n\n public constructor(options: TransportOptions, fetchImpl: FetchImpl = getNativeFetchImplementation()) {\n super(options);\n this._fetch = fetchImpl;\n }\n\n /**\n * @param sentryRequest Prepared SentryRequest to be delivered\n * @param originalPayload Original payload used to create SentryRequest\n */\n protected _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike {\n if (this._isRateLimited(sentryRequest.type)) {\n this.recordLostEvent('ratelimit_backoff', sentryRequest.type);\n\n return Promise.reject({\n event: originalPayload,\n type: sentryRequest.type,\n reason: `Transport for ${sentryRequest.type} requests locked till ${this._disabledUntil(\n sentryRequest.type,\n )} due to too many requests.`,\n status: 429,\n });\n }\n\n const options: RequestInit = {\n body: sentryRequest.body,\n method: 'POST',\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n referrerPolicy: (supportsReferrerPolicy() ? 'origin' : '') as ReferrerPolicy,\n };\n if (this.options.fetchParameters !== undefined) {\n Object.assign(options, this.options.fetchParameters);\n }\n if (this.options.headers !== undefined) {\n options.headers = this.options.headers;\n }\n\n return this._buffer\n .add(\n () =>\n new SyncPromise((resolve, reject) => {\n void this._fetch(sentryRequest.url, options)\n .then(response => {\n const headers = {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n };\n this._handleResponse({\n requestType: sentryRequest.type,\n response,\n headers,\n resolve,\n reject,\n });\n })\n .catch(reject);\n }),\n )\n .then(undefined, reason => {\n // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError.\n if (reason instanceof SentryError) {\n this.recordLostEvent('queue_overflow', sentryRequest.type);\n } else {\n this.recordLostEvent('network_error', sentryRequest.type);\n }\n throw reason;\n });\n }\n}\n","import { Event, Response, SentryRequest, Session } from '@sentry/types';\nimport { SentryError, SyncPromise } from '@sentry/utils';\n\nimport { BaseTransport } from './base';\n\n/** `XHR` based transport */\nexport class XHRTransport extends BaseTransport {\n /**\n * @param sentryRequest Prepared SentryRequest to be delivered\n * @param originalPayload Original payload used to create SentryRequest\n */\n protected _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike {\n if (this._isRateLimited(sentryRequest.type)) {\n this.recordLostEvent('ratelimit_backoff', sentryRequest.type);\n\n return Promise.reject({\n event: originalPayload,\n type: sentryRequest.type,\n reason: `Transport for ${sentryRequest.type} requests locked till ${this._disabledUntil(\n sentryRequest.type,\n )} due to too many requests.`,\n status: 429,\n });\n }\n\n return this._buffer\n .add(\n () =>\n new SyncPromise((resolve, reject) => {\n const request = new XMLHttpRequest();\n\n request.onreadystatechange = (): void => {\n if (request.readyState === 4) {\n const headers = {\n 'x-sentry-rate-limits': request.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': request.getResponseHeader('Retry-After'),\n };\n this._handleResponse({ requestType: sentryRequest.type, response: request, headers, resolve, reject });\n }\n };\n\n request.open('POST', sentryRequest.url);\n for (const header in this.options.headers) {\n if (Object.prototype.hasOwnProperty.call(this.options.headers, header)) {\n request.setRequestHeader(header, this.options.headers[header]);\n }\n }\n request.send(sentryRequest.body);\n }),\n )\n .then(undefined, reason => {\n // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError.\n if (reason instanceof SentryError) {\n this.recordLostEvent('queue_overflow', sentryRequest.type);\n } else {\n this.recordLostEvent('network_error', sentryRequest.type);\n }\n throw reason;\n });\n }\n}\n","import { BaseBackend } from '@sentry/core';\nimport { Event, EventHint, Options, Severity, Transport } from '@sentry/types';\nimport { supportsFetch } from '@sentry/utils';\n\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { FetchTransport, XHRTransport } from './transports';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see BrowserClient for more information.\n */\nexport interface BrowserOptions extends Options {\n /**\n * A pattern for error URLs which should exclusively be sent to Sentry.\n * This is the opposite of {@link Options.denyUrls}.\n * By default, all errors will be sent.\n */\n allowUrls?: Array;\n\n /**\n * A pattern for error URLs which should not be sent to Sentry.\n * To allow certain errors instead, use {@link Options.allowUrls}.\n * By default, all errors will be sent.\n */\n denyUrls?: Array;\n\n /** @deprecated use {@link Options.allowUrls} instead. */\n whitelistUrls?: Array;\n\n /** @deprecated use {@link Options.denyUrls} instead. */\n blacklistUrls?: Array;\n}\n\n/**\n * The Sentry Browser SDK Backend.\n * @hidden\n */\nexport class BrowserBackend extends BaseBackend {\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options, exception, hint);\n }\n /**\n * @inheritDoc\n */\n public eventFromMessage(message: string, level: Severity = Severity.Info, hint?: EventHint): PromiseLike {\n return eventFromMessage(this._options, message, level, hint);\n }\n\n /**\n * @inheritDoc\n */\n protected _setupTransport(): Transport {\n if (!this._options.dsn) {\n // We return the noop transport here in case there is no Dsn.\n return super._setupTransport();\n }\n\n const transportOptions = {\n ...this._options.transportOptions,\n dsn: this._options.dsn,\n tunnel: this._options.tunnel,\n sendClientReports: this._options.sendClientReports,\n _metadata: this._options._metadata,\n };\n\n if (this._options.transport) {\n return new this._options.transport(transportOptions);\n }\n if (supportsFetch()) {\n return new FetchTransport(transportOptions);\n }\n return new XHRTransport(transportOptions);\n }\n}\n","import { captureException, getReportDialogEndpoint, withScope } from '@sentry/core';\nimport { DsnLike, Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getGlobalObject,\n getOriginalFunction,\n isDebugBuild,\n logger,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nconst global = getGlobalObject();\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError += 1;\n setTimeout(() => {\n ignoreOnError -= 1;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const sentryWrapped: WrappedFunction = function (this: any): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope: Scope) => {\n scope.addEventProcessor((event: SentryEvent) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(): void;\n}\n\n/**\n * Injects the Report Dialog script\n * @hidden\n */\nexport function injectReportDialog(options: ReportDialogOptions = {}): void {\n if (!global.document) {\n return;\n }\n\n if (!options.eventId) {\n if (isDebugBuild()) {\n logger.error(`Missing eventId option in showReportDialog call`);\n }\n return;\n }\n\n if (!options.dsn) {\n if (isDebugBuild()) {\n logger.error(`Missing dsn option in showReportDialog call`);\n }\n return;\n }\n\n const script = global.document.createElement('script');\n script.async = true;\n script.src = getReportDialogEndpoint(options.dsn, options);\n\n if (options.onLoad) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n script.onload = options.onLoad;\n }\n\n const injectionPoint = global.document.head || global.document.body;\n\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n }\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Hub, Integration, Primitive, Severity } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addInstrumentationHandler,\n getLocationHref,\n isDebugBuild,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\n/** JSDoc */\ntype GlobalHandlersIntegrations = Record;\n\n/** Global handlers */\nexport class GlobalHandlers implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'GlobalHandlers';\n\n /**\n * @inheritDoc\n */\n public name: string = GlobalHandlers.id;\n\n /** JSDoc */\n private readonly _options: GlobalHandlersIntegrations;\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n private _installFunc: Record void) | undefined> = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };\n\n /** JSDoc */\n public constructor(options?: GlobalHandlersIntegrations) {\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n }\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key as GlobalHandlersIntegrationsOptionKeys];\n if (installFunc && options[key as GlobalHandlersIntegrationsOptionKeys]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key as GlobalHandlersIntegrationsOptionKeys] = undefined;\n }\n }\n }\n}\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler(): void {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data: { msg: any; url: any; line: any; column: any; error: any }) => {\n const [hub, attachStacktrace] = getHubAndAttachStacktrace();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(error || msg, undefined, {\n attachStacktrace,\n isRejection: false,\n }),\n url,\n line,\n column,\n );\n\n event.level = Severity.Error;\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler(): void {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e: any) => {\n const [hub, attachStacktrace] = getHubAndAttachStacktrace();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(error, undefined, {\n attachStacktrace,\n isRejection: true,\n });\n\n event.level = Severity.Error;\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n if (isDebugBuild()) {\n logger.log(`Global Handler attached: ${type}`);\n }\n}\n\nfunction addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndAttachStacktrace(): [Hub, boolean | undefined] {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const attachStacktrace = client && client.getOptions().attachStacktrace;\n return [hub, attachStacktrace];\n}\n","import { Integration, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getGlobalObject, getOriginalFunction } from '@sentry/utils';\n\nimport { wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\n/** JSDoc */\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nexport class TryCatch implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'TryCatch';\n\n /**\n * @inheritDoc\n */\n public name: string = TryCatch.id;\n\n /** JSDoc */\n private readonly _options: TryCatchOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n public setupOnce(): void {\n const global = getGlobalObject();\n\n if (this._options.setTimeout) {\n fill(global, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(global, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(global, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n}\n\n/** JSDoc */\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: true,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.call(\n this,\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n }),\n );\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const global = getGlobalObject() as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = global[target] && global[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: () => void): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n fn.handleEvent = wrap(fn.handleEvent.bind(fn), {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.call(\n this,\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n }),\n options,\n );\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable max-lines */\nimport { getCurrentHub } from '@sentry/core';\nimport { Event, Integration, Severity } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n getEventDescription,\n getGlobalObject,\n htmlTreeAsString,\n parseUrl,\n safeJoin,\n severityFromString,\n} from '@sentry/utils';\n\n/** JSDoc */\ninterface BreadcrumbsOptions {\n console: boolean;\n dom: boolean | { serializeAttribute: string | string[] };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nexport class Breadcrumbs implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Breadcrumbs';\n\n /**\n * @inheritDoc\n */\n public name: string = Breadcrumbs.id;\n\n /** JSDoc */\n private readonly _options: BreadcrumbsOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this._options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Create a breadcrumb of `sentry` from the events themselves\n */\n public addSentryBreadcrumb(event: Event): void {\n if (!this._options.sentry) {\n return;\n }\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n public setupOnce(): void {\n if (this._options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this._options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this._options.dom));\n }\n if (this._options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this._options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this._options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n }\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: { [key: string]: any }) => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function _innerDomBreadcrumb(handlerData: { [key: string]: any }): void {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = handlerData.event.target\n ? htmlTreeAsString(handlerData.event.target as Node, keyAttrs)\n : htmlTreeAsString(handlerData.event as unknown as Node, keyAttrs);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _consoleBreadcrumb(handlerData: { [key: string]: any }): void {\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _xhrBreadcrumb(handlerData: { [key: string]: any }): void {\n if (handlerData.endTimestamp) {\n // We only capture complete, non-sentry requests\n if (handlerData.xhr.__sentry_own_request__) {\n return;\n }\n\n const { method, url, status_code, body } = handlerData.xhr.__sentry_xhr__ || {};\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data: {\n method,\n url,\n status_code,\n },\n type: 'http',\n },\n {\n xhr: handlerData.xhr,\n input: body,\n },\n );\n\n return;\n }\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _fetchBreadcrumb(handlerData: { [key: string]: any }): void {\n // We only capture complete fetch requests\n if (!handlerData.endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data: handlerData.fetchData,\n level: Severity.Error,\n type: 'http',\n },\n {\n data: handlerData.error,\n input: handlerData.args,\n },\n );\n } else {\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data: {\n ...handlerData.fetchData,\n status_code: handlerData.response.status,\n },\n type: 'http',\n },\n {\n input: handlerData.args,\n response: handlerData.response,\n },\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _historyBreadcrumb(handlerData: { [key: string]: any }): void {\n const global = getGlobalObject();\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(global.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Exception, ExtendedError, Integration } from '@sentry/types';\nimport { isInstanceOf } from '@sentry/utils';\n\nimport { exceptionFromError } from '../parsers';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\ninterface LinkedErrorsOptions {\n key: string;\n limit: number;\n}\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = LinkedErrors.id;\n\n /**\n * @inheritDoc\n */\n private readonly _key: LinkedErrorsOptions['key'];\n\n /**\n * @inheritDoc\n */\n private readonly _limit: LinkedErrorsOptions['limit'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: Partial = {}) {\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n return self ? _handler(self._key, self._limit, event, hint) : event;\n });\n }\n}\n\n/**\n * @inheritDoc\n */\nexport function _handler(key: string, limit: number, event: Event, hint?: EventHint): Event | null {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n const linkedErrors = _walkErrorTree(limit, hint.originalException as ExtendedError, key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n}\n\n/**\n * JSDOC\n */\nexport function _walkErrorTree(limit: number, error: ExtendedError, key: string, stack: Exception[] = []): Exception[] {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {\n return stack;\n }\n const exception = exceptionFromError(error[key]);\n return _walkErrorTree(limit, error[key], key, [exception, ...stack]);\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { Event, Integration } from '@sentry/types';\nimport { getGlobalObject } from '@sentry/utils';\n\nconst global = getGlobalObject();\n\n/** UserAgent */\nexport class UserAgent implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'UserAgent';\n\n /**\n * @inheritDoc\n */\n public name: string = UserAgent.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n if (getCurrentHub().getIntegration(UserAgent)) {\n // if none of the information we want exists, don't bother\n if (!global.navigator && !global.location && !global.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (global.location && global.location.href);\n const { referrer } = global.document || {};\n const { userAgent } = global.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n}\n","import { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string = Dedupe.id;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((currentEvent: Event) => {\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n logger.warn(`Event dropped due to being a duplicate of previously captured event.`);\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n });\n }\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n } else if (event.stacktrace) {\n return event.stacktrace.frames;\n }\n return undefined;\n}\n","import { BaseClient, Scope, SDK_VERSION } from '@sentry/core';\nimport { Event, EventHint } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\n\nimport { BrowserBackend, BrowserOptions } from './backend';\nimport { injectReportDialog, ReportDialogOptions } from './helpers';\nimport { Breadcrumbs } from './integrations';\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserOptions = {}) {\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: 'npm:@sentry/browser',\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(BrowserBackend, options);\n }\n\n /**\n * Show a report dialog to the user to send feedback to a specific event.\n *\n * @param options Set individual options for the dialog\n */\n public showReportDialog(options: ReportDialogOptions = {}): void {\n // doesn't work without a document (React Native)\n const document = getGlobalObject().document;\n if (!document) {\n return;\n }\n\n if (!this._isEnabled()) {\n logger.error('Trying to call showReportDialog with Sentry Client disabled');\n return;\n }\n\n injectReportDialog({\n ...options,\n dsn: options.dsn || this.getDsn(),\n });\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, scope, hint);\n }\n\n /**\n * @inheritDoc\n */\n protected _sendEvent(event: Event): void {\n const integration = this.getIntegration(Breadcrumbs);\n if (integration) {\n integration.addSentryBreadcrumb(event);\n }\n super._sendEvent(event);\n }\n}\n","import { getCurrentHub, initAndBind, Integrations as CoreIntegrations } from '@sentry/core';\nimport { Hub } from '@sentry/types';\nimport { addInstrumentationHandler, getGlobalObject, isDebugBuild, logger, resolvedSyncPromise } from '@sentry/utils';\n\nimport { BrowserOptions } from './backend';\nimport { BrowserClient } from './client';\nimport { ReportDialogOptions, wrap as internalWrap } from './helpers';\nimport { Breadcrumbs, Dedupe, GlobalHandlers, LinkedErrors, TryCatch, UserAgent } from './integrations';\n\nexport const defaultIntegrations = [\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new UserAgent(),\n];\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n const window = getGlobalObject();\n // This supports the variable that sentry-webpack-plugin injects\n if (window.SENTRY_RELEASE && window.SENTRY_RELEASE.id) {\n options.release = window.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n initAndBind(BrowserClient, options);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nexport function showReportDialog(options: ReportDialogOptions = {}): void {\n const hub = getCurrentHub();\n const scope = hub.getScope();\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n const client = hub.getClient();\n if (client) {\n client.showReportDialog(options);\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function flush(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n if (isDebugBuild()) {\n logger.warn('Cannot flush events. No client defined.');\n }\n return resolvedSyncPromise(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function close(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n if (isDebugBuild()) {\n logger.warn('Cannot flush events and disable SDK. No client defined.');\n }\n return resolvedSyncPromise(false);\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\nfunction startSessionOnHub(hub: Hub): void {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n const window = getGlobalObject();\n const document = window.document;\n\n if (typeof document === 'undefined') {\n if (isDebugBuild()) {\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n }\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n","export * from './exports';\n\nimport { Integrations as CoreIntegrations } from '@sentry/core';\nimport { getGlobalObject } from '@sentry/utils';\n\nimport * as BrowserIntegrations from './integrations';\nimport * as Transports from './transports';\n\nlet windowIntegrations = {};\n\n// This block is needed to add compatibility with the integrations packages when used with a CDN\nconst _window = getGlobalObject();\nif (_window.Sentry && _window.Sentry.Integrations) {\n windowIntegrations = _window.Sentry.Integrations;\n}\n\nconst INTEGRATIONS = {\n ...windowIntegrations,\n ...CoreIntegrations,\n ...BrowserIntegrations,\n};\n\nexport { INTEGRATIONS as Integrations, Transports };\n","// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkInfo metadata\nexport const SDK_NAME = 'sentry.javascript.browser';\n","import { getCurrentHub } from '@sentry/hub';\nimport { Client, Options } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass = new (options: O) => F;\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nexport function initAndBind(clientClass: ClientClass, options: O): void {\n if (options.debug === true) {\n logger.enable();\n }\n const hub = getCurrentHub();\n const scope = hub.getScope();\n if (scope) {\n scope.update(options.initialScope);\n }\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n"],"names":["Severity","fallbackGlobalObject","getGlobalObject","window","self","objectToString","Object","prototype","toString","isError","wat","call","isInstanceOf","Error","isBuiltin","ty","isErrorEvent","isDOMError","isString","isPrimitive","isPlainObject","isEvent","Event","isElement","Element","isThenable","Boolean","then","base","_e","htmlTreeAsString","elem","keyAttrs","currentElem","out","height","len","sepLength","length","nextStr","_htmlElementAsString","push","parentNode","reverse","join","_oO","el","className","classes","key","attr","i","tagName","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","forEach","keyAttrPair","id","split","allowedAttrs","setPrototypeOf","__proto__","Array","obj","proto","prop","hasOwnProperty","message","_super","_this","name","_newTarget","constructor","__extends","DSN_REGEX","dsnToString","dsn","withPassword","host","path","pass","port","projectId","dsnFromComponents","components","publicKey","user","protocol","makeDsn","from","str","match","exec","SentryError","_a","_b","_c","slice","pop","projectMatch","dsnFromString","SeverityLevels","global","PREFIX","consoleSandbox","callback","originalConsole","console","wrappedLevels","level","__sentry_original__","result","keys","this","_enabled","Logger","_i","args","log","warn","error","__SENTRY__","logger","stripSentryFramesAndReverse","stack","localStack","firstFrameFunction","function","lastFrameFunction","indexOf","frame","filename","defaultFunctionName","getFunctionName","fn","e","truncate","max","substr","safeJoin","input","delimiter","isArray","output","value","String","isMatchingPattern","pattern","test","fill","source","replacementFactory","original","wrapped","markFunctionWrapped","_Oo","addNonEnumerableProperty","defineProperty","writable","configurable","getOriginalFunction","func","getWalkSource","err","event_1","type","target","currentTarget","CustomEvent","detail","jsonSize","encodeURI","utf8Length","JSON","stringify","normalizeToSize","object","depth","maxSize","serialized","normalize","normalizeValue","_events","document","walk","memo","hasWeakSet","inner","Infinity","WeakSet","has","add","delete","splice","normalized","serializeValue","toJSON","acc","innerKey","parse","extractExceptionKeysForMessage","exception","maxLength","sort","includedKeys","dropUndefinedKeys","val","rv","__values","supportsFetch","Headers","Request","Response","isNativeFetch","supportsReferrerPolicy","referrerPolicy","lastHref","handlers","instrumented","instrument","originalConsoleMethod","triggerHandlers","apply","instrumentConsole","triggerDOMHandler","bind","globalDOMEventHandler","makeDOMEventHandler","addEventListener","originalAddEventListener","listener","options","handlers_1","__sentry_instrumentation_handlers__","handlerForType","refCount","handler","originalRemoveEventListener","handlers_2","undefined","instrumentDOM","xhrproto","XMLHttpRequest","originalOpen","xhr","url","xhrInfo","__sentry_xhr__","method","toUpperCase","__sentry_own_request__","onreadystatechangeHandler","readyState","status_code","status","endTimestamp","Date","now","startTimestamp","onreadystatechange","readyStateArgs","originalSend","body","instrumentXHR","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","handlerData","fetchData","getFetchMethod","getFetchUrl","response","instrumentFetch","chrome","isChromePackagedApp","app","runtime","hasHistoryApi","history","pushState","replaceState","supportsHistory","oldOnPopState","onpopstate","historyReplacementFunction","originalHistoryFunction","to","location","href","instrumentHistory","_oldOnErrorHandler","onerror","msg","line","column","arguments","_oldOnUnhandledRejectionHandler","onunhandledrejection","addInstrumentationHandler","data","fetchArgs","debounceTimerID","lastCapturedEvent","globalListener","event","isContentEditable","shouldSkipDOMEvent","previous","current","shouldShortcircuitPreviousDebounce","clearTimeout","setTimeout","uuid4","crypto","msCrypto","getRandomValues","arr","Uint16Array","pad","num","v","replace","c","r","Math","random","parseUrl","query","fragment","relative","getFirstException","values","getEventDescription","eventId","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","checkOrSetAlreadyCaught","__sentry_captured__","resolvedSyncPromise","SyncPromise","resolve","rejectedSyncPromise","reason","_","reject","executor","_setResult","state","_state","_resolve","_reject","_value","_executeHandlers","cachedHandlers","_handlers","onfulfilled","onrejected","onfinally","isRejected","makePromiseBuffer","limit","buffer","remove","task","$","taskProducer","drain","timeout","counter","capturedSetTimeout","item","severityFromString","Warning","isSupportedSeverity","Log","dateTimestampSource","nowSeconds","platformPerformance","performance","timeOrigin","getBrowserPerformance","timestampSource","dateTimestampInSeconds","timestampInSeconds","threshold","performanceNow","dateNow","timeOriginDelta","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","Scope","scope","newScope","_breadcrumbs","_tags","_extra","_contexts","_user","_level","_span","_session","_transactionName","_fingerprint","_eventProcessors","_requestSession","_scopeListeners","update","_notifyScopeListeners","requestSession","tags","extras","extra","fingerprint","setTransactionName","context","span","getSpan","transaction","session","captureContext","updatedScope","contexts","breadcrumb","maxBreadcrumbs","maxCrumbs","min","mergedBreadcrumb","timestamp","__spread","hint","trace","getTraceContext","transactionName","_applyFingerprint","breadcrumbs","sdkProcessingMetadata","_sdkProcessingMetadata","_notifyEventProcessors","getGlobalEventProcessors","newData","processors","index","processor","final","_notifyingListeners","concat","globalEventProcessors","addGlobalEventProcessor","startingTime","started","Session","ipAddress","ip_address","did","email","username","ignoreDuration","sid","init","duration","release","environment","userAgent","errors","toISOString","attrs","user_agent","client","_version","getStackTop","bindClient","Hub","version","setupIntegrations","clone","getScope","getStack","getClient","pushScope","popScope","_stack","_lastEventId","event_id","finalHint","syntheticException","originalException","_invokeClient","beforeBreadcrumb","_d","finalBreadcrumb","addBreadcrumb","setUser","setTags","setExtras","setTag","setExtra","setContext","oldHub","makeMain","integration","getIntegration","_callExtensionMethod","customSamplingContext","endSession","_sendSessionUpdate","layer","getSession","close","setSession","getUser","currentSession","captureSession","carrier","getMainCarrier","sentry","extensions","hub","registry","getHubFromCarrier","setHubOnCarrier","getCurrentHub","isOlderThan","callOnHub","captureException","withScope","getBaseApiEndpoint","_getIngestEndpoint","_encodedAuth","sentry_key","sentry_version","encodeURIComponent","getStoreEndpointWithUrlEncodedAuth","getStoreEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnel","_getEnvelopeEndpoint","installedIntegrations","filterDuplicates","integrations","reduce","every","accIntegration","defaultIntegrations","userIntegrations","userIntegration","integrationsNames","alwaysLastToRun","getIntegrationsToSetup","setupOnce","setupIntegration","ALREADY_SEEN_ERROR","backendClass","_backend","_options","_dsn","BaseClient","_process","_getBackend","eventFromException","_captureEvent","promisedEvent","eventFromMessage","_isEnabled","_sendSession","getTransport","_isClientDoneProcessing","clientFinished","transportFlushed","flush","getOptions","enabled","_integrations","initialized","crashed","errored","exceptions","exceptions_1","sessionNonTerminal","Number","sendSession","ticked","interval","setInterval","_numProcessing","clearInterval","normalizeDepth","prepared","_applyClientOptions","_applyIntegrationsMetadata","finalScope","applyToEvent","evt","_normalizeEvent","b","baseClientNormalized","dist","maxValueLength","request","integrationsArray","sdk","sendEvent","_processEvent","finalEvent","beforeSend","sampleRate","transport","recordLostEvent","outcome","category","isTransaction","_prepareEvent","__sentry__","nullErr","_ensureBeforeSendRv","processedEvent","_updateSessionFromEvent","_sendEvent","promise","NoopTransport","_transport","_setupTransport","BaseBackend","_exception","_hint","_message","getSdkMetadataForEnvelopeHeader","api","metadata","eventToSentryRequest","sdkInfo","eventType","useEnvelope","samplingMethod","packages","enhanceEventWithSdkInfo","skippedNormalization","JSONStringifyError","newErr","innerErr","req","envelope","sent_at","sample_rates","rate","originalFunctionToString","SDK_VERSION","FunctionToString","Function","DEFAULT_IGNORE_ERRORS","InboundFilters","clientOptions","_mergeOptions","_shouldDropEvent","_isSentryError","_isIgnoredError","_isDeniedUrl","_isAllowedUrl","ignoreInternal","ignoreErrors","_getPossibleEventMessages","some","denyUrls","_getEventFilterUrl","allowUrls","whitelistUrls","blacklistUrls","oO","frames","stacktrace","_getLastValidUrl","frames_1","UNKNOWN_FUNCTION","createFrame","lineno","colno","in_app","chromeRegex","chromeEvalRegex","parts","subMatch","geckoREgex","geckoEvalRegex","gecko","winjsRegex","winjs","opera10Regex","opera10","opera11Regex","opera11","extractSafariExtensionDetails","isSafariExtension","isSafariWebExtension","exceptionFromError","ex","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","parsers","skipFirst","parsers_1","parser","createStackParser","eventFromUnknownInput","attachStacktrace","Info","eventFromString","domException","name_1","code","rejection","__serialized__","eventFromPlainObject","isRejection","synthetic","cachedFetchImpl","getNativeFetchImplementation","fetchImpl","sendReport","navigator","sendBeacon","fetch_1","credentials","keepalive","requestTypeToCategory","_api","_metadata","initDsn","sendClientReports","visibilityState","_flushOutcomes","BaseTransport","_sendRequest","sessionToSentryRequest","_buffer","_outcomes","outcomes","discarded_events","items","clientReportItem","discardedEvents","quantity","headers","serializedHeaders","itemHeaders","payload","serializeEnvelope","_handleRateLimit","requestType","_rateLimits","all","_disabledUntil","rlHeader","raHeader","trim","parameters","headerDelay","parseInt","delay","isNaN","header","headerDate","parseRetryAfterHeader","_fetch","FetchTransport","sentryRequest","originalPayload","_isRateLimited","Promise","fetchParameters","assign","get","_handleResponse","catch","XHRTransport","getResponseHeader","open","setRequestHeader","send","BrowserBackend","transportOptions","ignoreOnError","shouldIgnoreOnError","ignoreNextOnError","wrap","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","arg","addEventProcessor","property","getOwnPropertyDescriptor","injectReportDialog","script","async","src","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","injectionPoint","GlobalHandlers","_installGlobalOnErrorHandler","_installGlobalOnUnhandledRejectionHandler","stackTraceLimit","installFunc","_installFunc","globalHandlerLog","ERROR_TYPES_RE","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","addMechanismAndCapture","ev","ev0","ev0s","ev0sf","getLocationHref","captureEvent","getHubAndAttachStacktrace","DEFAULT_EVENT_TARGET","TryCatch","eventTarget","requestAnimationFrame","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","originalCallback","xmlHttpRequestProps","wrapOptions","originalFunction","eventName","handleEvent","wrappedEventHandler","originalEventHandler","Breadcrumbs","dom","_consoleBreadcrumb","_innerDomBreadcrumb","serializeAttribute","_domBreadcrumb","_xhrBreadcrumb","_fetchBreadcrumb","_historyBreadcrumb","parsedLoc","parsedFrom","parsedTo","LinkedErrors","_key","_limit","linkedErrors","_walkErrorTree","_handler","UserAgent","referrer","Referer","Dedupe","currentEvent","previousEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","_previousEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","BrowserClient","getDsn","platform","addSentryBreadcrumb","CoreIntegrations.InboundFilters","CoreIntegrations.FunctionToString","startSessionOnHub","startSession","windowIntegrations","_window","Sentry","Integrations","INTEGRATIONS","CoreIntegrations","BrowserIntegrations","window_1","SENTRY_RELEASE","autoSessionTracking","clientClass","debug","enable","initialScope","initAndBind","startSessionTracking","lastEventId","showReportDialog","internalWrap"],"mappings":";+dAGYA,m4BAAAA,EAAAA,aAAAA,8BAIVA,gBAEAA,oBAEAA,YAEAA,cAEAA,gBAEAA,sBCWF,IAAMC,EAAuB,YAObC,IACd,MAGwB,oBAAXC,OACPA,OACgB,oBAATC,KACPA,KACAH,ECrCR,IAAMI,EAAiBC,OAAOC,UAAUC,kBASxBC,EAAQC,GACtB,OAAQL,EAAeM,KAAKD,IAC1B,IAAK,iBACL,IAAK,qBACL,IAAK,wBACH,OAAO,EACT,QACE,OAAOE,EAAaF,EAAKG,QAI/B,SAASC,EAAUJ,EAAcK,GAC/B,OAAOV,EAAeM,KAAKD,KAAS,WAAWK,eAUjCC,EAAaN,GAC3B,OAAOI,EAAUJ,EAAK,uBAURO,EAAWP,GACzB,OAAOI,EAAUJ,EAAK,qBAqBRQ,EAASR,GACvB,OAAOI,EAAUJ,EAAK,mBAURS,EAAYT,GAC1B,OAAe,OAARA,GAAgC,iBAARA,GAAmC,mBAARA,WAU5CU,EAAcV,GAC5B,OAAOI,EAAUJ,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