{ "version": 3, "file": "bundle.tracing.min.js", "sources": [ "../../types/src/loglevel.ts", "../../types/src/session.ts", "../../types/src/severity.ts", "../../types/src/status.ts", "../../types/src/transaction.ts", "../../types/src/transport.ts", "../../utils/src/is.ts", "../../utils/src/browser.ts", "../../utils/src/polyfill.ts", "../../utils/src/error.ts", "../../utils/src/dsn.ts", "../../utils/src/node.ts", "../../utils/src/string.ts", "../../utils/src/misc.ts", "../../utils/src/logger.ts", "../../utils/src/memo.ts", "../../utils/src/stacktrace.ts", "../../utils/src/object.ts", "../../utils/src/supports.ts", "../../utils/src/instrument.ts", "../../utils/src/syncpromise.ts", "../../utils/src/promisebuffer.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", "../../browser/src/tracekit.ts", "../../browser/src/parsers.ts", "../../browser/src/eventbuilder.ts", "../../browser/src/transports/utils.ts", "../../utils/src/async.ts", "../../browser/src/transports/base.ts", "../../browser/src/transports/fetch.ts", "../../browser/src/transports/xhr.ts", "../../browser/src/backend.ts", "../../browser/src/helpers.ts", "../../browser/src/integrations/globalhandlers.ts", "../../browser/src/integrations/trycatch.ts", "../../browser/src/integrations/breadcrumbs.ts", "../../browser/src/integrations/linkederrors.ts", "../../browser/src/integrations/useragent.ts", "../../browser/src/integrations/dedupe.ts", "../../browser/src/client.ts", "../../browser/src/sdk.ts", "../../browser/src/index.ts", "../src/spanstatus.ts", "../src/utils.ts", "../src/errors.ts", "../src/span.ts", "../src/transaction.ts", "../src/idletransaction.ts", "../src/hubextensions.ts", "../src/browser/backgroundtab.ts", "../src/browser/web-vitals/lib/bindReporter.ts", "../src/browser/web-vitals/lib/initMetric.ts", "../src/browser/web-vitals/lib/generateUniqueID.ts", "../src/browser/web-vitals/lib/observe.ts", "../src/browser/web-vitals/lib/onHidden.ts", "../src/browser/web-vitals/lib/getVisibilityWatcher.ts", "../src/browser/web-vitals/getLCP.ts", "../src/browser/metrics.ts", "../src/browser/web-vitals/getCLS.ts", "../src/browser/web-vitals/getFID.ts", "../src/browser/request.ts", "../src/browser/router.ts", "../src/browser/browsertracing.ts", "../src/index.bundle.ts", "../../browser/src/version.ts", "../../core/src/sdk.ts" ], "sourcesContent": [ "/** Console logging verbosity for the SDK. */\nexport enum LogLevel {\n /** No logs will be generated. */\n None = 0,\n /** Only SDK internal errors will be logged. */\n Error = 1,\n /** Information useful for debugging the SDK will be logged. */\n Debug = 2,\n /** All SDK actions will be logged. */\n Verbose = 3,\n}\n", "import { User } from './user';\n\n/**\n * @inheritdoc\n */\nexport interface Session extends SessionContext {\n /** JSDoc */\n update(context?: SessionContext): void;\n\n /** JSDoc */\n close(status?: SessionStatus): void;\n\n /** JSDoc */\n 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}\n\nexport interface RequestSession {\n status?: RequestSessionStatus;\n}\n\n/**\n * Session Context\n */\nexport interface SessionContext {\n sid?: string;\n did?: string;\n init?: boolean;\n // seconds since the UNIX epoch\n timestamp?: number;\n // seconds since the UNIX epoch\n started?: number;\n duration?: number;\n status?: SessionStatus;\n release?: string;\n environment?: string;\n userAgent?: string;\n ipAddress?: string;\n errors?: number;\n user?: User | null;\n ignoreDuration?: boolean;\n}\n\n/**\n * Session Status\n */\nexport enum SessionStatus {\n /** JSDoc */\n Ok = 'ok',\n /** JSDoc */\n Exited = 'exited',\n /** JSDoc */\n Crashed = 'crashed',\n /** JSDoc */\n Abnormal = 'abnormal',\n}\n\nexport enum RequestSessionStatus {\n /** JSDoc */\n Ok = 'ok',\n /** JSDoc */\n Errored = 'errored',\n /** JSDoc */\n Crashed = 'crashed',\n}\n\n/** JSDoc */\nexport interface SessionAggregates {\n attrs?: {\n environment?: string;\n release?: string;\n };\n aggregates: Array;\n}\n\nexport interface SessionFlusherLike {\n /**\n * Increments the Session Status bucket in SessionAggregates Object corresponding to the status of the session\n * captured\n */\n incrementSessionStatusCount(): void;\n\n /** Submits the aggregates request mode sessions to Sentry */\n sendSessionAggregates(sessionAggregates: SessionAggregates): void;\n\n /** Empties Aggregate Buckets and Sends them to Transport Buffer */\n flush(): void;\n\n /** Clears setInterval and calls flush */\n close(): void;\n}\n\nexport interface AggregationCounts {\n started: string;\n errored?: number;\n exited?: number;\n crashed?: number;\n}\n", "/** JSDoc */\n// eslint-disable-next-line import/export\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// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace Severity {\n /**\n * Converts a string-based level into a {@link Severity}.\n *\n * @param level string representation of Severity\n * @returns Severity\n */\n export function fromString(level: string): Severity {\n switch (level) {\n case 'debug':\n return Severity.Debug;\n case 'info':\n return Severity.Info;\n case 'warn':\n case 'warning':\n return Severity.Warning;\n case 'error':\n return Severity.Error;\n case 'fatal':\n return Severity.Fatal;\n case 'critical':\n return Severity.Critical;\n case 'log':\n default:\n return Severity.Log;\n }\n }\n}\n", "/** The status of an event. */\n// eslint-disable-next-line import/export\nexport enum Status {\n /** The status could not be determined. */\n Unknown = 'unknown',\n /** The event was skipped due to configuration or callbacks. */\n Skipped = 'skipped',\n /** The event was sent to Sentry successfully. */\n Success = 'success',\n /** The client is currently rate limited and will try again later. */\n RateLimit = 'rate_limit',\n /** The event could not be processed. */\n Invalid = 'invalid',\n /** A server-side error occurred during submission. */\n Failed = 'failed',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace Status {\n /**\n * Converts a HTTP status code into a {@link Status}.\n *\n * @param code The HTTP response status code.\n * @returns The send status or {@link Status.Unknown}.\n */\n export function fromHttpCode(code: number): Status {\n if (code >= 200 && code < 300) {\n return Status.Success;\n }\n\n if (code === 429) {\n return Status.RateLimit;\n }\n\n if (code >= 400 && code < 500) {\n return Status.Invalid;\n }\n\n if (code >= 500) {\n return Status.Failed;\n }\n\n return Status.Unknown;\n }\n}\n", "import { ExtractedNodeRequestData, Primitive, WorkerLocation } from './misc';\nimport { Span, SpanContext } from './span';\n\n/**\n * Interface holding Transaction-specific properties\n */\nexport interface TransactionContext extends SpanContext {\n /**\n * Human-readable identifier for the transaction\n */\n name: string;\n\n /**\n * If true, sets the end timestamp of the transaction to the highest timestamp of child spans, trimming\n * the duration of the transaction. This is useful to discard extra time in the transaction that is not\n * accounted for in child spans, like what happens in the idle transaction Tracing integration, where we finish the\n * transaction after a given \"idle time\" and we don't want this \"idle time\" to be part of the transaction.\n */\n trimEnd?: boolean;\n\n /**\n * If this transaction has a parent, the parent's sampling decision\n */\n parentSampled?: boolean;\n\n /**\n * Metadata associated with the transaction, for internal SDK use.\n */\n metadata?: TransactionMetadata;\n}\n\n/**\n * Data pulled from a `sentry-trace` header\n */\nexport type TraceparentData = Pick;\n\n/**\n * Transaction \"Class\", inherits Span only has `setName`\n */\nexport interface Transaction extends TransactionContext, Span {\n /**\n * @inheritDoc\n */\n spanId: string;\n\n /**\n * @inheritDoc\n */\n traceId: string;\n\n /**\n * @inheritDoc\n */\n startTimestamp: number;\n\n /**\n * @inheritDoc\n */\n tags: { [key: string]: Primitive };\n\n /**\n * @inheritDoc\n */\n data: { [key: string]: any };\n\n /**\n * Metadata about the transaction\n */\n metadata: TransactionMetadata;\n\n /**\n * Set the name of the transaction\n */\n setName(name: string): void;\n\n /** Returns the current transaction properties as a `TransactionContext` */\n toContext(): TransactionContext;\n\n /** Updates the current transaction with a new `TransactionContext` */\n updateWithContext(transactionContext: TransactionContext): this;\n}\n\n/**\n * Context data passed by the user when starting a transaction, to be used by the tracesSampler method.\n */\nexport interface CustomSamplingContext {\n [key: string]: any;\n}\n\n/**\n * Data passed to the `tracesSampler` function, which forms the basis for whatever decisions it might make.\n *\n * Adds default data to data provided by the user. See {@link Hub.startTransaction}\n */\nexport interface SamplingContext extends CustomSamplingContext {\n /**\n * Context data with which transaction being sampled was created\n */\n transactionContext: TransactionContext;\n\n /**\n * Sampling decision from the parent transaction, if any.\n */\n parentSampled?: boolean;\n\n /**\n * Object representing the URL of the current page or worker script. Passed by default when using the `BrowserTracing`\n * integration.\n */\n location?: WorkerLocation;\n\n /**\n * Object representing the incoming request to a node server. Passed by default when using the TracingHandler.\n */\n request?: ExtractedNodeRequestData;\n}\n\nexport type Measurements = Record;\n\nexport enum TransactionSamplingMethod {\n Explicit = 'explicitly_set',\n Sampler = 'client_sampler',\n Rate = 'client_rate',\n Inheritance = 'inheritance',\n}\n\nexport interface TransactionMetadata {\n transactionSampling?: { rate?: number; method?: string };\n\n /** The two halves (sentry and third-party) of a transaction's tracestate header, used for dynamic sampling */\n tracestate?: {\n sentry?: string;\n thirdparty?: string;\n };\n\n /** For transactions tracing server-side request handling, the path of the request being tracked. */\n requestPath?: string;\n}\n", "import { DsnLike } from './dsn';\nimport { Event } from './event';\nimport { SentryRequestType } from './request';\nimport { Response } from './response';\nimport { SdkMetadata } from './sdkmetadata';\nimport { Session, SessionAggregates } from './session';\n\nexport enum Outcome {\n BeforeSend = 'before_send',\n EventProcessor = 'event_processor',\n NetworkError = 'network_error',\n QueueOverflow = 'queue_overflow',\n RateLimitBackoff = 'ratelimit_backoff',\n SampleRate = 'sample_rate',\n}\n\n/** Transport used sending data to Sentry */\nexport interface Transport {\n /**\n * Sends the event to the Store endpoint in Sentry.\n *\n * @param event Event that should be sent to Sentry.\n */\n sendEvent(event: Event): PromiseLike;\n\n /**\n * Sends the session to the Envelope endpoint in Sentry.\n *\n * @param session Session that should be sent to Sentry | Session Aggregates that should be sent to Sentry.\n */\n sendSession?(session: Session | SessionAggregates): PromiseLike;\n\n /**\n * Wait for all events to be sent or the timeout to expire, whichever comes first.\n *\n * @param timeout Maximum time in ms the transport should wait for events to be flushed. Omitting this parameter will\n * cause the transport to wait until all events are sent before resolving the promise.\n * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are\n * still events in the queue when the timeout is reached.\n */\n close(timeout?: number): PromiseLike;\n\n /**\n * Increment the counter for the specific client outcome\n */\n recordLostEvent?(type: Outcome, category: SentryRequestType): void;\n}\n\n/** JSDoc */\nexport type TransportClass = new (options: TransportOptions) => T;\n\n/** JSDoc */\nexport interface TransportOptions {\n /** Sentry DSN */\n dsn: DsnLike;\n /** Define custom headers */\n headers?: { [key: string]: string };\n /** Set a HTTP proxy that should be used for outbound requests. */\n httpProxy?: string;\n /** Set a HTTPS proxy that should be used for outbound requests. */\n httpsProxy?: string;\n /** HTTPS proxy certificates path */\n caCerts?: string;\n /** Fetch API init parameters */\n fetchParameters?: { [key: string]: string };\n /** The envelope tunnel to use. */\n tunnel?: string;\n /** Send SDK Client Reports. Enabled by default. */\n sendClientReports?: boolean;\n /**\n * Set of metadata about the SDK that can be internally used to enhance envelopes and events,\n * and provide additional data about every request.\n * */\n _metadata?: SdkMetadata;\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 * 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: any): boolean {\n switch (Object.prototype.toString.call(wat)) {\n case '[object Error]':\n return true;\n case '[object Exception]':\n return true;\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\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: any): boolean {\n return Object.prototype.toString.call(wat) === '[object 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: any): boolean {\n return Object.prototype.toString.call(wat) === '[object 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: any): boolean {\n return Object.prototype.toString.call(wat) === '[object 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: any): boolean {\n return Object.prototype.toString.call(wat) === '[object String]';\n}\n\n/**\n * Checks whether given value's 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: any): 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: any): boolean {\n return Object.prototype.toString.call(wat) === '[object 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: any): 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: any): 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: any): boolean {\n return Object.prototype.toString.call(wat) === '[object 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): boolean {\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: any): 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 { 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 = keyAttrs?.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (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", "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 // eslint-disable-next-line no-prototype-builtins\n if (!obj.hasOwnProperty(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 { SentryError } from './error';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+))?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\n/** Error message */\nconst ERROR_MESSAGE = 'Invalid Dsn';\n\n/** The Sentry Dsn, identifying a Sentry instance and project. */\nexport class Dsn implements DsnComponents {\n /** Protocol used to connect to Sentry. */\n public protocol!: DsnProtocol;\n /** Public authorization key (deprecated, renamed to publicKey). */\n public user!: string;\n /** Public authorization key. */\n public publicKey!: string;\n /** Private authorization key (deprecated, optional). */\n public pass!: string;\n /** Hostname of the Sentry instance. */\n public host!: string;\n /** Port of the Sentry instance. */\n public port!: string;\n /** Path */\n public path!: string;\n /** Project ID */\n public projectId!: string;\n\n /** Creates a new Dsn component */\n public constructor(from: DsnLike) {\n if (typeof from === 'string') {\n this._fromString(from);\n } else {\n this._fromComponents(from);\n }\n\n this._validate();\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 */\n public toString(withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = this;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n }\n\n /** Parses a string into this Dsn. */\n private _fromString(str: string): void {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new SentryError(ERROR_MESSAGE);\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 this._fromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n }\n\n /** Maps Dsn components into this instance. */\n private _fromComponents(components: DsnComponents): void {\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 this.user = components.publicKey || '';\n\n this.protocol = components.protocol;\n this.publicKey = components.publicKey || '';\n this.pass = components.pass || '';\n this.host = components.host;\n this.port = components.port || '';\n this.path = components.path || '';\n this.projectId = components.projectId;\n }\n\n /** Validates this Dsn and throws on error. */\n private _validate(): void {\n ['protocol', 'publicKey', 'host', 'projectId'].forEach(component => {\n if (!this[component as keyof DsnComponents]) {\n throw new SentryError(`${ERROR_MESSAGE}: ${component} missing`);\n }\n });\n\n if (!this.projectId.match(/^\\d+$/)) {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid projectId ${this.projectId}`);\n }\n\n if (this.protocol !== 'http' && this.protocol !== 'https') {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid protocol ${this.protocol}`);\n }\n\n if (this.port && isNaN(parseInt(this.port, 10))) {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid port ${this.port}`);\n }\n }\n}\n", "/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\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 ll = newLine.length;\n if (ll <= 150) {\n return newLine;\n }\n if (colno > ll) {\n // eslint-disable-next-line no-param-reassign\n colno = ll;\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, ll);\n if (end > ll - 5) {\n end = ll;\n }\n if (end === ll) {\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 < ll) {\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", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Event, Integration, StackFrame, WrappedFunction } from '@sentry/types';\n\nimport { isNodeEnv } from './node';\nimport { snipLine } from './string';\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 (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) as T & SentryGlobal;\n}\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(\n url: string,\n): {\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\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 if (event.message) {\n return event.message;\n }\n if (event.exception && event.exception.values && event.exception.values[0]) {\n const exception = event.exception.values[0];\n\n if (exception.type && exception.value) {\n return `${exception.type}: ${exception.value}`;\n }\n return exception.type || exception.value || event.event_id || '';\n }\n return event.event_id || '';\n}\n\n/** JSDoc */\ninterface ExtensibleConsole extends Console {\n [key: string]: any;\n}\n\n/** JSDoc */\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/**\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 event.exception = event.exception || {};\n event.exception.values = event.exception.values || [];\n event.exception.values[0] = event.exception.values[0] || {};\n event.exception.values[0].value = event.exception.values[0].value || value || '';\n event.exception.values[0].type = event.exception.values[0].type || type || 'Error';\n}\n\n/**\n * Adds exception mechanism to a given event.\n * @param event The event to modify.\n * @param mechanism Mechanism of the mechanism.\n * @hidden\n */\nexport function addExceptionMechanism(\n event: Event,\n mechanism: {\n [key: string]: any;\n } = {},\n): void {\n // TODO: Use real type with `keyof Mechanism` thingy and maybe make it better?\n try {\n // @ts-ignore Type 'Mechanism | {}' is not assignable to type 'Mechanism | undefined'\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values![0].mechanism = event.exception!.values![0].mechanism || {};\n Object.keys(mechanism).forEach(key => {\n // @ts-ignore Mechanism has no index signature\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values![0].mechanism[key] = mechanism[key];\n });\n } catch (_oO) {\n // no-empty\n }\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\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP = /^(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", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { consoleSandbox, getGlobalObject } from './misc';\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 */\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", "/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/**\n * Memo class used for decycle json objects. Uses WeakSet if available otherwise array.\n */\nexport class Memo {\n /** Determines if WeakSet is available */\n private readonly _hasWeakSet: boolean;\n /** Either WeakSet or Array */\n private readonly _inner: any;\n\n public constructor() {\n this._hasWeakSet = typeof WeakSet === 'function';\n this._inner = this._hasWeakSet ? new WeakSet() : [];\n }\n\n /**\n * Sets obj to remember.\n * @param obj Object to remember\n */\n public memoize(obj: any): boolean {\n if (this._hasWeakSet) {\n if (this._inner.has(obj)) {\n return true;\n }\n this._inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < this._inner.length; i++) {\n const value = this._inner[i];\n if (value === obj) {\n return true;\n }\n }\n this._inner.push(obj);\n return false;\n }\n\n /**\n * Removes object from internal storage.\n * @param obj Object to forget\n */\n public unmemoize(obj: any): void {\n if (this._hasWeakSet) {\n this._inner.delete(obj);\n } else {\n for (let i = 0; i < this._inner.length; i++) {\n if (this._inner[i] === obj) {\n this._inner.splice(i, 1);\n break;\n }\n }\n }\n }\n}\n", "const 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", "/* 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 { Memo } 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 wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __sentry_original__: {\n enumerable: false,\n value: original,\n },\n });\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 * 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(\n value: any,\n): {\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 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 const type = Object.prototype.toString.call(value);\n\n // Node.js REPL notation\n if (typeof value === 'string') {\n return value;\n }\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: Memo = new Memo()): any {\n // If we reach the maximum depth, serialize whatever has 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 we can just bail out, as theres no point in going down that branch any further\n const normalized = normalizeValue(value, key);\n if (isPrimitive(normalized)) {\n return normalized;\n }\n\n // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys: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.memoize(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.unmemoize(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", "import { logger } from './logger';\nimport { getGlobalObject } from './misc';\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 logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\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 // https://caniuse.com/#feat=referrer-policy\n // It doesn't. And it throw 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 @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport { WrappedFunction } from '@sentry/types';\n\nimport { isInstanceOf, isString } from './is';\nimport { logger } from './logger';\nimport { getGlobalObject } from './misc';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\n\nconst global = getGlobalObject();\n\n/** Object describing handler that will be triggered for a given `type` of instrumentation */\ninterface InstrumentHandler {\n type: InstrumentHandlerType;\n callback: InstrumentHandlerCallback;\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(handler: InstrumentHandler): void {\n if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') {\n return;\n }\n handlers[handler.type] = handlers[handler.type] || [];\n (handlers[handler.type] as InstrumentHandlerCallback[]).push(handler.callback);\n instrument(handler.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 logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(\n handler,\n )}\\nError: ${e}`,\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(originalConsoleLevel: () => any): Function {\n return function(...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleLevel) {\n Function.prototype.apply.call(originalConsoleLevel, 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 // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately.\n const requestKeys: XMLHttpRequest[] = [];\n const requestValues: Array[] = [];\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 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) && xhr.__sentry_xhr__.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 if (xhr.__sentry_xhr__) {\n xhr.__sentry_xhr__.status_code = xhr.status;\n }\n } catch (e) {\n /* do nothing */\n }\n\n try {\n const requestPos = requestKeys.indexOf(xhr);\n if (requestPos !== -1) {\n // Make sure to pop both key and value to keep it in sync.\n requestKeys.splice(requestPos);\n const args = requestValues.splice(requestPos)[0];\n if (xhr.__sentry_xhr__ && args[0] !== undefined) {\n xhr.__sentry_xhr__.body = args[0] as XHRSendInput;\n }\n }\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 requestKeys.push(this);\n requestValues.push(args);\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(proto, 'removeEventListener', 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\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", "/* 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 */\nenum States {\n /** Pending */\n PENDING = 'PENDING',\n /** Resolved / OK */\n RESOLVED = 'RESOLVED',\n /** Rejected / Error */\n REJECTED = 'REJECTED',\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<{\n done: boolean;\n onfulfilled?: ((value: T) => T | PromiseLike) | null;\n onrejected?: ((reason: any) => any) | null;\n }> = [];\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 static resolve(value: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n }\n\n /** JSDoc */\n public static reject(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n }\n\n /** JSDoc */\n public static all(collection: Array>): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n if (!Array.isArray(collection)) {\n reject(new TypeError(`Promise.all requires an array as input.`));\n return;\n }\n\n if (collection.length === 0) {\n resolve([]);\n return;\n }\n\n let counter = collection.length;\n const resolvedCollection: U[] = [];\n\n collection.forEach((item, index) => {\n void SyncPromise.resolve(item)\n .then(value => {\n resolvedCollection[index] = value;\n counter -= 1;\n\n if (counter !== 0) {\n return;\n }\n resolve(resolvedCollection);\n })\n .then(null, reject);\n });\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._attachHandler({\n done: false,\n onfulfilled: result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n return;\n }\n try {\n resolve(onfulfilled(result));\n return;\n } catch (e) {\n reject(e);\n return;\n }\n },\n onrejected: reason => {\n if (!onrejected) {\n reject(reason);\n return;\n }\n try {\n resolve(onrejected(reason));\n return;\n } catch (e) {\n reject(e);\n return;\n }\n },\n });\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 public toString(): string {\n return '[object SyncPromise]';\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 // TODO: FIXME\n /** JSDoc */\n private readonly _attachHandler = (handler: {\n /** JSDoc */\n done: boolean;\n /** JSDoc */\n onfulfilled?(value: T): any;\n /** JSDoc */\n onrejected?(reason: any): any;\n }) => {\n this._handlers = this._handlers.concat(handler);\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.done) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n if (handler.onfulfilled) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler.onfulfilled((this._value as unknown) as any);\n }\n }\n\n if (this._state === States.REJECTED) {\n if (handler.onrejected) {\n handler.onrejected(this._value);\n }\n }\n\n handler.done = true;\n });\n };\n}\n\nexport { SyncPromise };\n", "import { SentryError } from './error';\nimport { SyncPromise } from './syncpromise';\n\n/** A simple queue that holds promises. */\nexport class PromiseBuffer {\n /** Internal set of queued Promises */\n private readonly _buffer: Array> = [];\n\n public constructor(protected _limit?: number) {}\n\n /**\n * Says if the buffer is ready to take more requests\n */\n public isReady(): boolean {\n return this._limit === undefined || this.length() < this._limit;\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 public add(taskProducer: () => PromiseLike): PromiseLike {\n if (!this.isReady()) {\n return SyncPromise.reject(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 (this._buffer.indexOf(task) === -1) {\n this._buffer.push(task);\n }\n void task\n .then(() => this.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 this.remove(task).then(null, () => {\n // We have to add another catch here because `this.remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n public remove(task: PromiseLike): PromiseLike {\n const removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0];\n return removedTask;\n }\n\n /**\n * This function returns the number of unresolved promises in the queue.\n */\n public length(): number {\n return this._buffer.length;\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 public drain(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\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 void SyncPromise.all(this._buffer)\n .then(() => {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n })\n .then(null, () => {\n resolve(true);\n });\n });\n }\n}\n", "import { getGlobalObject } from './misc';\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 * 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 will be a transaction, but it's not guaranteed to be\n const span = this.getSpan() as undefined | (Span & { spanRecorder: { spans: Span[] } });\n\n // try it the new way first\n if (span?.transaction) {\n return span?.transaction;\n }\n\n // fallback to the old way (known bug: this only finds transactions with sampled = true)\n if (span?.spanRecorder?.spans[0]) {\n return span.spanRecorder.spans[0] as Transaction;\n }\n\n // neither way found a transaction\n return undefined;\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?.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 return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\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 = 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 === SessionStatus.Ok) {\n this.update({ status: SessionStatus.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: dropUndefinedKeys({\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 SessionStatus,\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 = 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 = 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 = 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 this.getStackTop()\n ?.scope?.getSession()\n ?.close();\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n this.getStackTop()?.scope?.setSession();\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 === SessionStatus.Ok) {\n currentSession.update({ status: SessionStatus.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 activeDomain = getMainCarrier().__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 level 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 { DsnLike, SdkMetadata } from '@sentry/types';\nimport { Dsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\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 **/\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: Dsn;\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 = new Dsn(dsn);\n this.metadata = metadata;\n this._tunnel = tunnel;\n }\n\n /** Returns the Dsn object. */\n public getDsn(): Dsn {\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 const dsn = this.getDsn();\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 store endpoint URL. */\n public getStoreEndpoint(): string {\n return this._getIngestEndpoint('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 */\n public getStoreEndpointWithUrlEncodedAuth(): string {\n return `${this.getStoreEndpoint()}?${this._encodedAuth()}`;\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 if (this.forceEnvelope()) {\n return this._tunnel as string;\n }\n\n return `${this._getEnvelopeEndpoint()}?${this._encodedAuth()}`;\n }\n\n /** Returns only the path component for the store endpoint. */\n public getStoreEndpointPath(): string {\n const dsn = this.getDsn();\n return `${dsn.path ? `/${dsn.path}` : ''}/api/${dsn.projectId}/store/`;\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 */\n public getRequestHeaders(clientName: string, clientVersion: string): { [key: string]: string } {\n // CHANGE THIS to use metadata but keep clientName and clientVersion compatible\n const dsn = this.getDsn();\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. */\n public getReportDialogEndpoint(\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 = this.getDsn();\n const endpoint = `${this.getBaseApiEndpoint()}embed/error-page/`;\n\n const encodedOptions = [];\n encodedOptions.push(`dsn=${dsn.toString()}`);\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.push(`name=${encodeURIComponent(dialogOptions.user.name)}`);\n }\n if (dialogOptions.user.email) {\n encodedOptions.push(`email=${encodeURIComponent(dialogOptions.user.email)}`);\n }\n } else {\n encodedOptions.push(`${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`);\n }\n }\n if (encodedOptions.length) {\n return `${endpoint}?${encodedOptions.join('&')}`;\n }\n\n return endpoint;\n }\n\n /** Returns the envelope endpoint URL. */\n private _getEnvelopeEndpoint(): string {\n return this._getIngestEndpoint('envelope');\n }\n\n /** Returns the ingest API endpoint for target. */\n private _getIngestEndpoint(target: 'store' | 'envelope'): string {\n if (this._tunnel) {\n return this._tunnel;\n }\n const base = this.getBaseApiEndpoint();\n const dsn = this.getDsn();\n return `${base}${dsn.projectId}/${target}/`;\n }\n\n /** Returns a URL-encoded string with auth config suitable for a query string. */\n private _encodedAuth(): string {\n const dsn = this.getDsn();\n const auth = {\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 return urlEncode(auth);\n }\n}\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Integration, Options } from '@sentry/types';\nimport { 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 Object.defineProperty(integrations, 'initialized', { value: true });\n return integrations;\n}\n", "/* eslint-disable max-lines */\nimport { Scope, Session } from '@sentry/hub';\nimport {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n Options,\n Outcome,\n SessionStatus,\n Severity,\n Transport,\n} from '@sentry/types';\nimport {\n dateTimestampInSeconds,\n Dsn,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n normalize,\n SentryError,\n SyncPromise,\n truncate,\n uuid4,\n} from '@sentry/utils';\n\nimport { Backend, BackendClass } from './basebackend';\nimport { IntegrationIndex, setupIntegrations } from './integration';\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?: Dsn;\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 = new Dsn(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 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 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 logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n logger.warn('Discarded session because of missing or non-string release');\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(): Dsn | 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 === SessionStatus.Ok;\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n session.update({\n ...(crashed && { status: SessionStatus.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 = SyncPromise.resolve(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 (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 const { _experiments = {} } = this.getOptions();\n if (_experiments.ensureNoCircularStructures) {\n return normalize(normalized);\n }\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 if (!this._isEnabled()) {\n return SyncPromise.reject(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 transport.recordLostEvent?.(Outcome.SampleRate, 'event');\n return SyncPromise.reject(\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 transport.recordLostEvent?.(Outcome.EventProcessor, 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 this._ensureBeforeSendRv(beforeSendResult);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n transport.recordLostEvent?.(Outcome.BeforeSend, 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 * Verifies that return value of configured `beforeSend` is of expected type.\n */\n protected _ensureBeforeSendRv(\n rv: PromiseLike | Event | null,\n ): PromiseLike | Event | null {\n const nullErr = '`beforeSend` method has to return `null` or a valid event.';\n if (isThenable(rv)) {\n return (rv as PromiseLike).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}\n", "import { Event, Response, Status, Transport } from '@sentry/types';\nimport { SyncPromise } from '@sentry/utils';\n\n/** Noop transport */\nexport class NoopTransport implements Transport {\n /**\n * @inheritDoc\n */\n public sendEvent(_: Event): PromiseLike {\n return SyncPromise.resolve({\n reason: `NoopTransport: Event has been skipped because no Dsn is configured.`,\n status: Status.Skipped,\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(_?: number): PromiseLike {\n return SyncPromise.resolve(true);\n }\n}\n", "import { Event, EventHint, Options, Session, Severity, Transport } from '@sentry/types';\nimport { 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 a {@link Event} from an exception. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n eventFromException(exception: any, hint?: EventHint): PromiseLike;\n\n /** Creates a {@link Event} from a plain message. */\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 logger.error(`Error while sending event: ${reason}`);\n });\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session): void {\n if (!this._transport.sendSession) {\n logger.warn(\"Dropping session because custom transport doesn't implement sendSession\");\n return;\n }\n\n void this._transport.sendSession(session).then(null, reason => {\n logger.error(`Error while sending session: ${reason}`);\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';\n\nimport { API } from './api';\n\n/** Extract sdk info from from the API metadata */\nfunction getSdkMetadataForEnvelopeHeader(api: API): 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: API): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const envelopeHeaders = JSON.stringify({\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(api.forceEnvelope() && { dsn: api.getDsn().toString() }),\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: api.getEnvelopeEndpointWithUrlEncodedAuth(),\n };\n}\n\n/** Creates a SentryRequest from an event. */\nexport function eventToSentryRequest(event: Event, api: API): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const eventType = event.type || 'event';\n const useEnvelope = eventType === 'transaction' || api.forceEnvelope();\n\n const { transactionSampling, ...metadata } = event.debug_meta || {};\n const { method: samplingMethod, rate: sampleRate } = transactionSampling || {};\n if (Object.keys(metadata).length === 0) {\n delete event.debug_meta;\n } else {\n event.debug_meta = metadata;\n }\n\n const req: SentryRequest = {\n body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),\n type: eventType,\n url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(),\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.forceEnvelope() && { dsn: api.getDsn().toString() }),\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';\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 = this.__sentry_original__ || this;\n return originalFunctionToString.apply(context, args);\n };\n }\n}\n", "export const SDK_VERSION = '6.13.3';\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Event, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, 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 logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (this._isIgnoredError(event, options)) {\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (this._isDeniedUrl(event, options)) {\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${this._getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!this._isAllowedUrl(event, options)) {\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 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 return (\n (event &&\n event.exception &&\n event.exception.values &&\n event.exception.values[0] &&\n event.exception.values[0].type === 'SentryError') ||\n false\n );\n } catch (_oO) {\n return false;\n }\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 logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\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?.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 const frames = event.stacktrace.frames;\n return this._getLastValidUrl(frames);\n }\n if (event.exception) {\n const frames =\n event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames;\n return this._getLastValidUrl(frames);\n }\n return null;\n } catch (oO) {\n logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n }\n}\n", "/**\n * This was originally forked from https://github.com/occ/TraceKit, but has since been\n * largely modified and is now maintained as part of Sentry JS SDK.\n */\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access, max-lines */\n\n/**\n * An object representing a single stack frame.\n * {Object} StackFrame\n * {string} url The JavaScript or HTML file URL.\n * {string} func The function name, or empty for anonymous functions (if guessing did not work).\n * {string[]?} args The arguments passed to the function, if known.\n * {number=} line The line number, if known.\n * {number=} column The column number, if known.\n * {string[]} context An array of source code lines; the middle element corresponds to the correct line#.\n */\nexport interface StackFrame {\n url: string;\n func: string;\n args: string[];\n line: number | null;\n column: number | null;\n}\n\n/**\n * An object representing a JavaScript stack trace.\n * {Object} StackTrace\n * {string} name The name of the thrown exception.\n * {string} message The exception error message.\n * {TraceKit.StackFrame[]} stack An array of stack frames.\n */\nexport interface StackTrace {\n name: string;\n message: string;\n mechanism?: string;\n stack: StackFrame[];\n failed?: boolean;\n}\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chrome = /^\\s*at (?:(.*?) ?\\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack||[-a-z]+:|.*bundle|\\/).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\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 gecko = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst winjs = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\nconst geckoEval = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nconst chromeEval = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\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\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function computeStackTrace(ex: any): StackTrace {\n let stack = null;\n let popSize = 0;\n\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n popSize = ex.framesToPop;\n } else if (reactMinifiedRegexp.test(ex.message)) {\n popSize = 1;\n }\n }\n\n try {\n // This must be tried first because Opera 10 *destroys*\n // its stacktrace property if you try to access the stack\n // property first!!\n stack = computeStackTraceFromStacktraceProp(ex);\n if (stack) {\n return popFrames(stack, popSize);\n }\n } catch (e) {\n // no-empty\n }\n\n try {\n stack = computeStackTraceFromStackProp(ex);\n if (stack) {\n return popFrames(stack, popSize);\n }\n } catch (e) {\n // no-empty\n }\n\n return {\n message: extractMessage(ex),\n name: ex && ex.name,\n stack: [],\n failed: true,\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, complexity\nfunction computeStackTraceFromStackProp(ex: any): StackTrace | null {\n if (!ex || !ex.stack) {\n return null;\n }\n\n const stack = [];\n const lines = ex.stack.split('\\n');\n let isEval;\n let submatch;\n let parts;\n let element;\n\n for (let i = 0; i < lines.length; ++i) {\n if ((parts = chrome.exec(lines[i]))) {\n const isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n if (isEval && (submatch = chromeEval.exec(parts[2]))) {\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 // Arpad: Working with the regexp above is super painful. it is quite a hack, but just stripping the `address at `\n // prefix here seems like the quickest solution for now.\n let url = parts[2] && parts[2].indexOf('address at ') === 0 ? parts[2].substr('address at '.length) : parts[2];\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 let func = parts[1] || UNKNOWN_FUNCTION;\n [func, url] = extractSafariExtensionDetails(func, url);\n\n element = {\n url,\n func,\n args: isNative ? [parts[2]] : [],\n line: parts[3] ? +parts[3] : null,\n column: parts[4] ? +parts[4] : null,\n };\n } else if ((parts = winjs.exec(lines[i]))) {\n element = {\n url: parts[2],\n func: parts[1] || UNKNOWN_FUNCTION,\n args: [],\n line: +parts[3],\n column: parts[4] ? +parts[4] : null,\n };\n } else if ((parts = gecko.exec(lines[i]))) {\n isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval && (submatch = geckoEval.exec(parts[3]))) {\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 } else if (i === 0 && !parts[5] && ex.columnNumber !== void 0) {\n // FireFox uses this awesome columnNumber property for its top frame\n // Also note, Firefox's column number is 0-based and everything else expects 1-based,\n // so adding 1\n // NOTE: this hack doesn't work if top-most frame is eval\n stack[0].column = (ex.columnNumber as number) + 1;\n }\n\n let url = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, url] = extractSafariExtensionDetails(func, url);\n\n element = {\n url,\n func,\n args: parts[2] ? parts[2].split(',') : [],\n line: parts[4] ? +parts[4] : null,\n column: parts[5] ? +parts[5] : null,\n };\n } else {\n continue;\n }\n\n if (!element.func && element.line) {\n element.func = UNKNOWN_FUNCTION;\n }\n\n stack.push(element);\n }\n\n if (!stack.length) {\n return null;\n }\n\n return {\n message: extractMessage(ex),\n name: ex.name,\n stack,\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction computeStackTraceFromStacktraceProp(ex: any): StackTrace | null {\n if (!ex || !ex.stacktrace) {\n return null;\n }\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;\n const opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n const opera11Regex = / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\((.*)\\))? in (.*):\\s*$/i;\n const lines = stacktrace.split('\\n');\n const stack = [];\n let parts;\n\n for (let line = 0; line < lines.length; line += 2) {\n let element = null;\n if ((parts = opera10Regex.exec(lines[line]))) {\n element = {\n url: parts[2],\n func: parts[3],\n args: [],\n line: +parts[1],\n column: null,\n };\n } else if ((parts = opera11Regex.exec(lines[line]))) {\n element = {\n url: parts[6],\n func: parts[3] || parts[4],\n args: parts[5] ? parts[5].split(',') : [],\n line: +parts[1],\n column: +parts[2],\n };\n }\n\n if (element) {\n if (!element.func && element.line) {\n element.func = UNKNOWN_FUNCTION;\n }\n stack.push(element);\n }\n }\n\n if (!stack.length) {\n return null;\n }\n\n return {\n message: extractMessage(ex),\n name: ex.name,\n stack,\n };\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 * Unfortunatelly \"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, url: 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:${url}` : `safari-web-extension:${url}`,\n ]\n : [func, url];\n};\n\n/** Remove N number of frames from the stack */\nfunction popFrames(stacktrace: StackTrace, popSize: number): StackTrace {\n try {\n return {\n ...stacktrace,\n stack: stacktrace.stack.slice(popSize),\n };\n } catch (e) {\n return stacktrace;\n }\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, Exception, StackFrame } from '@sentry/types';\nimport { extractExceptionKeysForMessage, isEvent, normalizeToSize } from '@sentry/utils';\n\nimport { computeStackTrace, StackFrame as TraceKitStackFrame, StackTrace as TraceKitStackTrace } from './tracekit';\n\nconst STACKTRACE_LIMIT = 50;\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 exceptionFromStacktrace(stacktrace: TraceKitStackTrace): Exception {\n const frames = prepareFramesForEvent(stacktrace.stack);\n\n const exception: Exception = {\n type: stacktrace.name,\n value: stacktrace.message,\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 stacktrace = computeStackTrace(syntheticException);\n const frames = prepareFramesForEvent(stacktrace.stack);\n event.stacktrace = {\n frames,\n };\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromStacktrace(stacktrace: TraceKitStackTrace): Event {\n const exception = exceptionFromStacktrace(stacktrace);\n\n return {\n exception: {\n values: [exception],\n },\n };\n}\n\n/**\n * @hidden\n */\nexport function prepareFramesForEvent(stack: TraceKitStackFrame[]): StackFrame[] {\n if (!stack || !stack.length) {\n return [];\n }\n\n let localStack = stack;\n\n const firstFrameFunction = localStack[0].func || '';\n const lastFrameFunction = localStack[localStack.length - 1].func || '';\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(\n (frame: TraceKitStackFrame): StackFrame => ({\n colno: frame.column === null ? undefined : frame.column,\n filename: frame.url || localStack[0].url,\n function: frame.func || '?',\n in_app: true,\n lineno: frame.line === null ? undefined : frame.line,\n }),\n )\n .reverse();\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 SyncPromise,\n} from '@sentry/utils';\n\nimport { eventFromPlainObject, eventFromStacktrace, prepareFramesForEvent } from './parsers';\nimport { computeStackTrace } from './tracekit';\n\n/**\n * Builds and Event from a Exception\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, {\n handled: true,\n type: 'generic',\n });\n event.level = Severity.Error;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return SyncPromise.resolve(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 SyncPromise.resolve(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n exception: unknown,\n syntheticException?: Error,\n options: {\n rejection?: 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 // eslint-disable-next-line no-param-reassign\n exception = errorEvent.error;\n event = eventFromStacktrace(computeStackTrace(exception as Error));\n return event;\n }\n if (isDOMError(exception as DOMError) || isDOMException(exception as DOMException)) {\n // If it is a DOMError or DOMException (which are legacy APIs, but still supported in some browsers)\n // then we just extract the name, code, and message, as they don't provide anything else\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n const domException = exception as DOMException;\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n\n event = eventFromString(message, syntheticException, options);\n addExceptionTypeValue(event, message);\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 event = eventFromStacktrace(computeStackTrace(exception as Error));\n return event;\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it is plain Object or Event, serialize it manually and extract options\n // This will allow us to group events based on top-level keys\n // which is much better than creating new group when any key/value change\n const objectException = exception as Record;\n event = eventFromPlainObject(objectException, syntheticException, options.rejection);\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 stacktrace = computeStackTrace(syntheticException);\n const frames = prepareFramesForEvent(stacktrace.stack);\n event.stacktrace = {\n frames,\n };\n }\n\n return event;\n}\n", "import { forget, getGlobalObject, 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 (typeof document?.createElement === `function`) {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n if (sandbox.contentWindow?.fetch) {\n fetchImpl = sandbox.contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\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 { API } from '@sentry/core';\nimport {\n Event,\n Outcome,\n Response as SentryResponse,\n SentryRequestType,\n Status,\n Transport,\n TransportOptions,\n} from '@sentry/types';\nimport {\n dateTimestampInSeconds,\n getGlobalObject,\n logger,\n parseRetryAfterHeader,\n PromiseBuffer,\n SentryError,\n} from '@sentry/utils';\n\nimport { sendReport } from './utils';\n\nconst CATEGORY_MAPPING: {\n [key in SentryRequestType]: string;\n} = {\n event: 'error',\n transaction: 'transaction',\n session: 'session',\n attachment: 'attachment',\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: API;\n\n /** A simple buffer holding all requests. */\n protected readonly _buffer: PromiseBuffer = new PromiseBuffer(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 = new API(options.dsn, options._metadata, options.tunnel);\n // eslint-disable-next-line deprecation/deprecation\n this.url = this._api.getStoreEndpointWithUrlEncodedAuth();\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): PromiseLike {\n throw new SentryError('Transport Class has to implement `sendEvent` method');\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 = `${CATEGORY_MAPPING[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 = this._api.getEnvelopeEndpointWithUrlEncodedAuth();\n // Envelope header is required to be at least an empty object\n const envelopeHeader = JSON.stringify({});\n const itemHeaders = JSON.stringify({\n type: 'client_report',\n });\n const item = JSON.stringify({\n timestamp: dateTimestampInSeconds(),\n discarded_events: Object.keys(outcomes).map(key => {\n const [category, reason] = key.split(':');\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n }),\n });\n const envelope = `${envelopeHeader}\\n${itemHeaders}\\n${item}`;\n\n try {\n sendReport(url, 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 = Status.fromHttpCode(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)\n logger.warn(`Too many ${requestType} requests, backing off until: ${this._disabledUntil(requestType)}`);\n\n if (status === 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 = CATEGORY_MAPPING[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", "import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';\nimport { Event, Outcome, 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 * @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 * @param sentryRequest Prepared SentryRequest to be delivered\n * @param originalPayload Original payload used to create SentryRequest\n */\n private _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike {\n if (this._isRateLimited(sentryRequest.type)) {\n this.recordLostEvent(Outcome.RateLimitBackoff, 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 // https://caniuse.com/#feat=referrer-policy\n // It doesn't. And it throw 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(Outcome.QueueOverflow, sentryRequest.type);\n } else {\n this.recordLostEvent(Outcome.NetworkError, sentryRequest.type);\n }\n throw reason;\n });\n }\n}\n", "import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';\nimport { Event, Outcome, 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 * @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 * @param sentryRequest Prepared SentryRequest to be delivered\n * @param originalPayload Original payload used to create SentryRequest\n */\n private _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike {\n if (this._isRateLimited(sentryRequest.type)) {\n this.recordLostEvent(Outcome.RateLimitBackoff, 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 (this.options.headers.hasOwnProperty(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(Outcome.QueueOverflow, sentryRequest.type);\n } else {\n this.recordLostEvent(Outcome.NetworkError, 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 { API, captureException, withScope } from '@sentry/core';\nimport { DsnLike, Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';\nimport { addExceptionMechanism, addExceptionTypeValue, getGlobalObject, logger } 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 if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // We don't wanna wrap it twice\n if (fn.__sentry__) {\n return fn;\n }\n\n // If this has already been wrapped in the past, return that wrapped function\n if (fn.__sentry_wrapped__) {\n return fn.__sentry_wrapped__;\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 if (fn.handleEvent) {\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 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return fn.handleEvent.apply(this, wrappedArguments);\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 const processedEvent = { ...event };\n\n if (options.mechanism) {\n addExceptionTypeValue(processedEvent, undefined, undefined);\n addExceptionMechanism(processedEvent, options.mechanism);\n }\n\n processedEvent.extra = {\n ...processedEvent.extra,\n arguments: args,\n };\n\n return processedEvent;\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 fn.prototype = fn.prototype || {};\n sentryWrapped.prototype = fn.prototype;\n\n Object.defineProperty(fn, '__sentry_wrapped__', {\n enumerable: false,\n value: sentryWrapped,\n });\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 Object.defineProperties(sentryWrapped, {\n __sentry__: {\n enumerable: false,\n value: true,\n },\n __sentry_original__: {\n enumerable: false,\n value: fn,\n },\n });\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 logger.error(`Missing eventId option in showReportDialog call`);\n return;\n }\n\n if (!options.dsn) {\n logger.error(`Missing dsn option in showReportDialog call`);\n return;\n }\n\n const script = global.document.createElement('script');\n script.async = true;\n script.src = new API(options.dsn).getReportDialogEndpoint(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, Integration, Primitive, Severity } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\n/** JSDoc */\ninterface GlobalHandlersIntegrations {\n onerror: boolean;\n onunhandledrejection: boolean;\n}\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 /** JSDoc */\n private _onErrorHandlerInstalled: boolean = false;\n\n /** JSDoc */\n private _onUnhandledRejectionHandlerInstalled: boolean = false;\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\n if (this._options.onerror) {\n logger.log('Global Handler attached: onerror');\n this._installGlobalOnErrorHandler();\n }\n\n if (this._options.onunhandledrejection) {\n logger.log('Global Handler attached: onunhandledrejection');\n this._installGlobalOnUnhandledRejectionHandler();\n }\n }\n\n /** JSDoc */\n private _installGlobalOnErrorHandler(): void {\n if (this._onErrorHandlerInstalled) {\n return;\n }\n\n addInstrumentationHandler({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: (data: { msg: any; url: any; line: any; column: any; error: any }) => {\n const error = data.error;\n const currentHub = getCurrentHub();\n const hasIntegration = currentHub.getIntegration(GlobalHandlers);\n const isFailedOwnDelivery = error && error.__sentry_own_request__ === true;\n\n if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {\n return;\n }\n\n const client = currentHub.getClient();\n const event =\n error === undefined && isString(data.msg)\n ? this._eventFromIncompleteOnError(data.msg, data.url, data.line, data.column)\n : this._enhanceEventWithInitialFrame(\n eventFromUnknownInput(error || data.msg, undefined, {\n attachStacktrace: client && client.getOptions().attachStacktrace,\n rejection: false,\n }),\n data.url,\n data.line,\n data.column,\n );\n\n addExceptionMechanism(event, {\n handled: false,\n type: 'onerror',\n });\n\n currentHub.captureEvent(event, {\n originalException: error,\n });\n },\n type: 'error',\n });\n\n this._onErrorHandlerInstalled = true;\n }\n\n /** JSDoc */\n private _installGlobalOnUnhandledRejectionHandler(): void {\n if (this._onUnhandledRejectionHandlerInstalled) {\n return;\n }\n\n addInstrumentationHandler({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: (e: any) => {\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 const currentHub = getCurrentHub();\n const hasIntegration = currentHub.getIntegration(GlobalHandlers);\n const isFailedOwnDelivery = error && error.__sentry_own_request__ === true;\n\n if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {\n return true;\n }\n\n const client = currentHub.getClient();\n const event = isPrimitive(error)\n ? this._eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(error, undefined, {\n attachStacktrace: client && client.getOptions().attachStacktrace,\n rejection: true,\n });\n\n event.level = Severity.Error;\n\n addExceptionMechanism(event, {\n handled: false,\n type: 'onunhandledrejection',\n });\n\n currentHub.captureEvent(event, {\n originalException: error,\n });\n\n return;\n },\n type: 'unhandledrejection',\n });\n\n this._onUnhandledRejectionHandlerInstalled = true;\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\n private _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE = /^(?:[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;\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 || 'Error',\n value: message,\n },\n ],\n },\n };\n\n return this._enhanceEventWithInitialFrame(event, url, line, column);\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 */\n private _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 /** JSDoc */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n event.exception = event.exception || {};\n event.exception.values = event.exception.values || [];\n event.exception.values[0] = event.exception.values[0] || {};\n event.exception.values[0].stacktrace = event.exception.values[0].stacktrace || {};\n event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.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 if (event.exception.values[0].stacktrace.frames.length === 0) {\n event.exception.values[0].stacktrace.frames.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n }\n}\n", "import { Integration, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getGlobalObject } 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', this._wrapTimeFunction.bind(this));\n }\n\n if (this._options.setInterval) {\n fill(global, 'setInterval', this._wrapTimeFunction.bind(this));\n }\n\n if (this._options.requestAnimationFrame) {\n fill(global, 'requestAnimationFrame', this._wrapRAF.bind(this));\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) {\n fill(XMLHttpRequest.prototype, 'send', this._wrapXHR.bind(this));\n }\n\n if (this._options.eventTarget) {\n const eventTarget = Array.isArray(this._options.eventTarget) ? this._options.eventTarget : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(this._wrapEventTarget.bind(this));\n }\n }\n\n /** JSDoc */\n private _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\n private _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 */\n private _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\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function(\n original: () => void,\n ): (eventName: string, fn: EventListenerObject, options?: boolean | AddEventListenerOptions) => 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(proto, 'removeEventListener', 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?.__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 /** JSDoc */\n private _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 if (original.__sentry_original__) {\n wrapOptions.mechanism.data.handler = getFunctionName(original.__sentry_original__);\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", "/* 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} 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({\n callback: (...args) => {\n this._consoleBreadcrumb(...args);\n },\n type: 'console',\n });\n }\n if (this._options.dom) {\n addInstrumentationHandler({\n callback: (...args) => {\n this._domBreadcrumb(...args);\n },\n type: 'dom',\n });\n }\n if (this._options.xhr) {\n addInstrumentationHandler({\n callback: (...args) => {\n this._xhrBreadcrumb(...args);\n },\n type: 'xhr',\n });\n }\n if (this._options.fetch) {\n addInstrumentationHandler({\n callback: (...args) => {\n this._fetchBreadcrumb(...args);\n },\n type: 'fetch',\n });\n }\n if (this._options.history) {\n addInstrumentationHandler({\n callback: (...args) => {\n this._historyBreadcrumb(...args);\n },\n type: 'history',\n });\n }\n }\n\n /**\n * Creates breadcrumbs from console API calls\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _consoleBreadcrumb(handlerData: { [key: string]: any }): void {\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: Severity.fromString(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 DOM API calls\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _domBreadcrumb(handlerData: { [key: string]: any }): void {\n let target;\n let keyAttrs = typeof this._options.dom === 'object' ? this._options.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 /**\n * Creates breadcrumbs from XHR API calls\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _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\n private _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\n private _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}\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Exception, ExtendedError, Integration } from '@sentry/types';\nimport { isInstanceOf } from '@sentry/utils';\n\nimport { exceptionFromStacktrace } from '../parsers';\nimport { computeStackTrace } from '../tracekit';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\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: string;\n\n /**\n * @inheritDoc\n */\n private readonly _limit: number;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { key?: string; limit?: number } = {}) {\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 if (self) {\n const handler = self._handler && self._handler.bind(self);\n return typeof handler === 'function' ? handler(event, hint) : event;\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n private _handler(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 = this._walkErrorTree(hint.originalException as ExtendedError, this._key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n }\n\n /**\n * @inheritDoc\n */\n private _walkErrorTree(error: ExtendedError, key: string, stack: Exception[] = []): Exception[] {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {\n return stack;\n }\n const stacktrace = computeStackTrace(error[key]);\n const exception = exceptionFromStacktrace(stacktrace);\n return this._walkErrorTree(error[key], key, [exception, ...stack]);\n }\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?.url || global.location?.href;\n const { referrer } = global.document || {};\n const { userAgent } = global.navigator || {};\n\n const headers = {\n ...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 (self._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 /** JSDoc */\n private _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (this._isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (this._isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n }\n\n /** JSDoc */\n private _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 (!this._isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!this._isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n }\n\n /** JSDoc */\n private _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\n /** JSDoc */\n private _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = this._getFramesFromEvent(currentEvent);\n let previousFrames = this._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 */\n private _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n }\n\n /** JSDoc */\n private _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = this._getExceptionFromEvent(previousEvent);\n const currentException = this._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 (!this._isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!this._isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n }\n\n /** JSDoc */\n private _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", "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 { addInstrumentationHandler, getGlobalObject, logger, SyncPromise } 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 logger.warn('Cannot flush events. No client defined.');\n return SyncPromise.resolve(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 logger.warn('Cannot flush events and disable SDK. No client defined.');\n return SyncPromise.resolve(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\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 logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\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 (typeof hub.startSession !== 'function' || typeof hub.captureSession !== 'function') {\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 hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler({\n callback: ({ 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 return;\n }\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n },\n type: 'history',\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", "/** The status of an Span. */\n// eslint-disable-next-line import/export\nexport enum SpanStatus {\n /** The operation completed successfully. */\n Ok = 'ok',\n /** Deadline expired before operation could complete. */\n DeadlineExceeded = 'deadline_exceeded',\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n Unauthenticated = 'unauthenticated',\n /** 403 Forbidden */\n PermissionDenied = 'permission_denied',\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n NotFound = 'not_found',\n /** 429 Too Many Requests */\n ResourceExhausted = 'resource_exhausted',\n /** Client specified an invalid argument. 4xx. */\n InvalidArgument = 'invalid_argument',\n /** 501 Not Implemented */\n Unimplemented = 'unimplemented',\n /** 503 Service Unavailable */\n Unavailable = 'unavailable',\n /** Other/generic 5xx. */\n InternalError = 'internal_error',\n /** Unknown. Any non-standard HTTP status code. */\n UnknownError = 'unknown_error',\n /** The operation was cancelled (typically by the user). */\n Cancelled = 'cancelled',\n /** Already exists (409) */\n AlreadyExists = 'already_exists',\n /** Operation was rejected because the system is not in a state required for the operation's */\n FailedPrecondition = 'failed_precondition',\n /** The operation was aborted, typically due to a concurrency issue. */\n Aborted = 'aborted',\n /** Operation was attempted past the valid range. */\n OutOfRange = 'out_of_range',\n /** Unrecoverable data loss or corruption */\n DataLoss = 'data_loss',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace SpanStatus {\n /**\n * Converts a HTTP status code into a {@link SpanStatus}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or {@link SpanStatus.UnknownError}.\n */\n export function fromHttpCode(httpStatus: number): SpanStatus {\n if (httpStatus < 400) {\n return SpanStatus.Ok;\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return SpanStatus.Unauthenticated;\n case 403:\n return SpanStatus.PermissionDenied;\n case 404:\n return SpanStatus.NotFound;\n case 409:\n return SpanStatus.AlreadyExists;\n case 413:\n return SpanStatus.FailedPrecondition;\n case 429:\n return SpanStatus.ResourceExhausted;\n default:\n return SpanStatus.InvalidArgument;\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return SpanStatus.Unimplemented;\n case 503:\n return SpanStatus.Unavailable;\n case 504:\n return SpanStatus.DeadlineExceeded;\n default:\n return SpanStatus.InternalError;\n }\n }\n\n return SpanStatus.UnknownError;\n }\n}\n", "import { getCurrentHub, Hub } from '@sentry/hub';\nimport { Options, TraceparentData, Transaction } from '@sentry/types';\n\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n options: Options | undefined = getCurrentHub()\n .getClient()\n ?.getOptions(),\n): boolean {\n if (!options) {\n return false;\n }\n return 'tracesSampleRate' in options || 'tracesSampler' in options;\n}\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent: string): TraceparentData | undefined {\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (matches) {\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n }\n return undefined;\n}\n\n/** Grabs active transaction off scope, if any */\nexport function getActiveTransaction(hub: Hub = getCurrentHub()): T | undefined {\n return hub?.getScope()?.getTransaction() as T | undefined;\n}\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nexport function msToSec(time: number): number {\n return time / 1000;\n}\n\n/**\n * Converts from seconds to milliseconds\n * @param time time in seconds\n */\nexport function secToMs(time: number): number {\n return time * 1000;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n", "import { addInstrumentationHandler, logger } from '@sentry/utils';\n\nimport { SpanStatus } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n addInstrumentationHandler({\n callback: errorCallback,\n type: 'error',\n });\n addInstrumentationHandler({\n callback: errorCallback,\n type: 'unhandledrejection',\n });\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n logger.log(`[Tracing] Transaction: ${SpanStatus.InternalError} -> Global error occured`);\n activeTransaction.setStatus(SpanStatus.InternalError);\n }\n}\n", "/* eslint-disable max-lines */\nimport { Primitive, Span as SpanInterface, SpanContext, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys, timestampWithMs, uuid4 } from '@sentry/utils';\n\nimport { SpanStatus } from './spanstatus';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[] = [];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * @inheritDoc\n */\n public traceId: string = uuid4();\n\n /**\n * @inheritDoc\n */\n public spanId: string = uuid4().substring(16);\n\n /**\n * @inheritDoc\n */\n public parentSpanId?: string;\n\n /**\n * Internal keeper of the status\n */\n public status?: SpanStatus | string;\n\n /**\n * @inheritDoc\n */\n public sampled?: boolean;\n\n /**\n * Timestamp in seconds when the span was created.\n */\n public startTimestamp: number = timestampWithMs();\n\n /**\n * Timestamp in seconds when the span ended.\n */\n public endTimestamp?: number;\n\n /**\n * @inheritDoc\n */\n public op?: string;\n\n /**\n * @inheritDoc\n */\n public description?: string;\n\n /**\n * @inheritDoc\n */\n public tags: { [key: string]: Primitive } = {};\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any } = {};\n\n /**\n * List of spans that were finalized\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n */\n public transaction?: Transaction;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext?: SpanContext) {\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated\n */\n public child(\n spanContext?: Pick>,\n ): Span {\n return this.startChild(spanContext);\n }\n\n /**\n * @inheritDoc\n */\n public startChild(\n spanContext?: Pick>,\n ): Span {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public setData(key: string, value: any): this {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatus): this {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setHttpStatus(httpStatus: number): this {\n this.setTag('http.status_code', String(httpStatus));\n const spanStatus = SpanStatus.fromHttpCode(httpStatus);\n if (spanStatus !== SpanStatus.UnknownError) {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public isSuccess(): boolean {\n return this.status === SpanStatus.Ok;\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): void {\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n }\n\n /**\n * @inheritDoc\n */\n public toTraceparent(): string {\n let sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return `${this.traceId}-${this.spanId}${sampledString}`;\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(spanContext: SpanContext): this {\n this.data = spanContext.data ?? {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId ?? this.spanId;\n this.startTimestamp = spanContext.startTimestamp ?? this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags ?? {};\n this.traceId = spanContext.traceId ?? this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getTraceContext(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n status?: string;\n tags?: { [key: string]: Primitive };\n trace_id: string;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public toJSON(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n start_timestamp: number;\n status?: string;\n tags?: { [key: string]: Primitive };\n timestamp?: number;\n trace_id: string;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n }\n}\n", "import { getCurrentHub, Hub } from '@sentry/hub';\nimport {\n Event,\n Measurements,\n Outcome,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, isInstanceOf, logger } from '@sentry/utils';\n\nimport { Span as SpanClass, SpanRecorder } from './span';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n public name: string;\n\n public metadata: TransactionMetadata;\n\n private _measurements: Measurements = {};\n\n /**\n * The reference to the current hub.\n */\n private readonly _hub: Hub = (getCurrentHub() as unknown) as Hub;\n\n private _trimEnd?: boolean;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n\n if (isInstanceOf(hub, Hub)) {\n this._hub = hub as Hub;\n }\n\n this.name = transactionContext.name || '';\n\n this.metadata = transactionContext.metadata || {};\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n }\n\n /**\n * JSDoc\n */\n public setName(name: string): void {\n this.name = name;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Set observed measurements for this transaction.\n * @hidden\n */\n public setMeasurements(measurements: Measurements): void {\n this._measurements = { ...measurements };\n }\n\n /**\n * Set metadata for this transaction.\n * @hidden\n */\n public setMetadata(newMetadata: TransactionMetadata): void {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): string | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n logger.warn('Transaction has no name, falling back to ``.');\n this.name = '';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n this._hub\n .getClient()\n ?.getTransport?.()\n .recordLostEvent?.(Outcome.SampleRate, 'transaction');\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev: SpanClass, current: SpanClass) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const transaction: Event = {\n contexts: {\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n debug_meta: this.metadata,\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2));\n transaction.measurements = this._measurements;\n }\n\n logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name ?? '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { TransactionContext } from '@sentry/types';\nimport { logger, timestampWithMs } from '@sentry/utils';\n\nimport { Span, SpanRecorder } from './span';\nimport { SpanStatus } from './spanstatus';\nimport { Transaction } from './transaction';\n\nexport const DEFAULT_IDLE_TIMEOUT = 1000;\nexport const HEARTBEAT_INTERVAL = 5000;\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string = '',\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp?: number) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record = {};\n\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number = 0;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean = false;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[] = [];\n\n /**\n * If a transaction is created and no activities are added, we want to make sure that\n * it times out properly. This is cleared and not used when activities are added.\n */\n private _initTimeout: ReturnType | undefined;\n\n public constructor(\n transactionContext: TransactionContext,\n private readonly _idleHub?: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished.\n * @default 1000\n */\n private readonly _idleTimeout: number = DEFAULT_IDLE_TIMEOUT,\n // If an idle transaction should be put itself on and off the scope automatically.\n private readonly _onScope: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n if (_idleHub && _onScope) {\n // There should only be one active transaction on the scope\n clearActiveTransaction(_idleHub);\n\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._initTimeout = setTimeout(() => {\n if (!this._finished) {\n this.finish();\n }\n }, this._idleTimeout);\n }\n\n /** {@inheritDoc} */\n public finish(endTimestamp: number = timestampWithMs()): string | undefined {\n this._finished = true;\n this.activities = {};\n\n if (this.spanRecorder) {\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus(SpanStatus.Cancelled);\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n logger.log(\n '[Tracing] discarding Span since it happened after Transaction was finished',\n JSON.stringify(span, undefined, 2),\n );\n }\n return keepSpan;\n });\n\n logger.log('[Tracing] flushing IdleTransaction');\n } else {\n logger.log('[Tracing] No active IdleTransaction');\n }\n\n // this._onScope is true if the transaction was previously on the scope.\n if (this._onScope) {\n clearActiveTransaction(this._idleHub);\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n if (this._initTimeout) {\n clearTimeout(this._initTimeout);\n this._initTimeout = undefined;\n }\n logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const timeout = this._idleTimeout;\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampWithMs is in seconds, timeout is in ms\n const end = timestampWithMs() + timeout / 1000;\n\n setTimeout(() => {\n if (!this._finished) {\n this.finish(end);\n }\n }, timeout);\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter += 1;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n logger.log(`[Tracing] Transaction finished because of no change for 3 heart beats`);\n this.setStatus(SpanStatus.DeadlineExceeded);\n this.setTag('heartbeat', 'failed');\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, HEARTBEAT_INTERVAL);\n }\n}\n\n/**\n * Reset active transaction on scope\n */\nfunction clearActiveTransaction(hub?: Hub): void {\n if (hub) {\n const scope = hub.getScope();\n if (scope) {\n const transaction = scope.getTransaction();\n if (transaction) {\n scope.setSpan(undefined);\n }\n }\n }\n}\n", "import { getMainCarrier, Hub } from '@sentry/hub';\nimport {\n CustomSamplingContext,\n Integration,\n IntegrationClass,\n Options,\n SamplingContext,\n TransactionContext,\n TransactionSamplingMethod,\n} from '@sentry/types';\nimport { dynamicRequire, isNodeEnv, loadModule, logger } from '@sentry/utils';\n\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { Transaction } from './transaction';\nimport { hasTracingEnabled } from './utils';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n const scope = this.getScope();\n if (scope) {\n const span = scope.getSpan();\n if (span) {\n return {\n 'sentry-trace': span.toTraceparent(),\n };\n }\n }\n return {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param hub: The hub off of which to read config options\n * @param transaction: The transaction needing a sampling decision\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample(transaction: T, options: Options, samplingContext: SamplingContext): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n transactionSampling: { method: TransactionSamplingMethod.Explicit },\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n transactionSampling: {\n method: TransactionSamplingMethod.Sampler,\n // cast to number in case it's a boolean\n rate: Number(sampleRate),\n },\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n transaction.setMetadata({\n transactionSampling: { method: TransactionSamplingMethod.Inheritance },\n });\n } else {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n transactionSampling: {\n method: TransactionSamplingMethod.Rate,\n // cast to number in case it's a boolean\n rate: Number(sampleRate),\n },\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n logger.warn(`[Tracing] Discarding transaction because of invalid sample rate.`);\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate as any) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n const options = this.getClient()?.getOptions() || {};\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments?.maxSpans as number);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout?: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n): IdleTransaction {\n const options = hub.getClient()?.getOptions() || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments?.maxSpans as number);\n }\n return transaction;\n}\n\n/**\n * @private\n */\nexport function _addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n}\n\n/**\n * @private\n */\nfunction _autoloadDatabaseIntegrations(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n\n const packageToIntegrationMapping: Record Integration> = {\n mongodb() {\n const integration = dynamicRequire(module, './integrations/mongo') as { Mongo: IntegrationClass };\n return new integration.Mongo();\n },\n mongoose() {\n const integration = dynamicRequire(module, './integrations/mongo') as { Mongo: IntegrationClass };\n return new integration.Mongo({ mongoose: true });\n },\n mysql() {\n const integration = dynamicRequire(module, './integrations/mysql') as { Mysql: IntegrationClass };\n return new integration.Mysql();\n },\n pg() {\n const integration = dynamicRequire(module, './integrations/postgres') as {\n Postgres: IntegrationClass;\n };\n return new integration.Postgres();\n },\n };\n\n const mappedPackages = Object.keys(packageToIntegrationMapping)\n .filter(moduleName => !!loadModule(moduleName))\n .map(pkg => {\n try {\n return packageToIntegrationMapping[pkg]();\n } catch (e) {\n return undefined;\n }\n })\n .filter(p => p) as Integration[];\n\n if (mappedPackages.length > 0) {\n carrier.__SENTRY__.integrations = [...(carrier.__SENTRY__.integrations || []), ...mappedPackages];\n }\n}\n\n/**\n * This patches the global object and injects the Tracing extensions methods\n */\nexport function addExtensionMethods(): void {\n _addTracingExtensions();\n\n // Detect and automatically load specified integrations.\n if (isNodeEnv()) {\n _autoloadDatabaseIntegrations();\n }\n\n // If an error happens globally, we should make sure transaction status is set to error.\n registerErrorInstrumentation();\n}\n", "import { getGlobalObject, logger } from '@sentry/utils';\n\nimport { IdleTransaction } from '../idletransaction';\nimport { SpanStatus } from '../spanstatus';\nimport { getActiveTransaction } from '../utils';\n\nconst global = getGlobalObject();\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (global && global.document) {\n global.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (global.document.hidden && activeTransaction) {\n logger.log(\n `[Tracing] Transaction: ${SpanStatus.Cancelled} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(SpanStatus.Cancelled);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Metric, ReportHandler } from '../types';\n\nexport const bindReporter = (\n callback: ReportHandler,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n metric.delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (metric.delta || prevValue === undefined) {\n prevValue = metric.value;\n callback(metric);\n }\n }\n }\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n return {\n name,\n value: value ?? -1,\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v2-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (type: string, callback: PerformanceEntryHandler): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n // More extensive feature detect needed for Firefox due to:\n // https://github.com/GoogleChrome/web-vitals/issues/142\n if (type === 'first-input' && !('PerformanceEventTiming' in self)) {\n return;\n }\n\n const po: PerformanceObserver = new PerformanceObserver(l => l.getEntries().map(callback));\n\n po.observe({ type, buffered: true });\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobalObject } from '@sentry/utils';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || getGlobalObject().document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobalObject } from '@sentry/utils';\n\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): number => {\n return getGlobalObject().document.visibilityState === 'hidden' ? 0 : Infinity;\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { ReportHandler } from './types';\n\n// https://wicg.github.io/largest-contentful-paint/#sec-largest-contentful-paint-interface\nexport interface LargestContentfulPaint extends PerformanceEntry {\n renderTime: DOMHighResTimeStamp;\n loadTime: DOMHighResTimeStamp;\n size: number;\n id: string;\n url: string;\n element?: Element;\n toJSON(): Record;\n}\n\nconst reportedMetricIDs: Record = {};\n\nexport const getLCP = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const entryHandler = (entry: PerformanceEntry): void => {\n // The startTime attribute returns the value of the renderTime if it is not 0,\n // and the value of the loadTime otherwise.\n const value = entry.startTime;\n\n // If the page was hidden prior to paint time of the entry,\n // ignore it and mark the metric as final, otherwise add the entry.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries.push(entry);\n }\n\n if (report) {\n report();\n }\n };\n\n const po = observe('largest-contentful-paint', entryHandler);\n\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n }\n};\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Measurements, SpanContext } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, getGlobalObject, htmlTreeAsString, isNodeEnv, logger } from '@sentry/utils';\n\nimport { Span } from '../span';\nimport { Transaction } from '../transaction';\nimport { msToSec } from '../utils';\nimport { getCLS, LayoutShift } from './web-vitals/getCLS';\nimport { getFID } from './web-vitals/getFID';\nimport { getLCP, LargestContentfulPaint } from './web-vitals/getLCP';\nimport { getVisibilityWatcher } from './web-vitals/lib/getVisibilityWatcher';\nimport { NavigatorDeviceMemory, NavigatorNetworkInformation } from './web-vitals/types';\n\nconst global = getGlobalObject();\n\n/**\n * Exports a way to add options to our metric collection. Currently experimental.\n */\nexport interface MetricsInstrumentationOptions {\n _reportAllChanges: boolean;\n}\n\nexport const DEFAULT_METRICS_INSTR_OPTIONS: MetricsInstrumentationOptions = {\n _reportAllChanges: false,\n};\n\n/** Class tracking metrics */\nexport class MetricsInstrumentation {\n private _measurements: Measurements = {};\n\n private _performanceCursor: number = 0;\n private _lcpEntry: LargestContentfulPaint | undefined;\n private _clsEntry: LayoutShift | undefined;\n\n public constructor(_options: MetricsInstrumentationOptions) {\n if (!isNodeEnv() && global?.performance && global?.document) {\n if (global.performance.mark) {\n global.performance.mark('sentry-tracing-init');\n }\n\n this._trackCLS();\n this._trackLCP(_options._reportAllChanges);\n this._trackFID();\n }\n }\n\n /** Add performance related spans to a transaction */\n public addPerformanceEntries(transaction: Transaction): void {\n if (!global || !global.performance || !global.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n logger.log('[Tracing] Adding & adjusting spans using Performance API');\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n let entryScriptSrc: string | undefined;\n\n if (global.document && global.document.scripts) {\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < global.document.scripts.length; i++) {\n // We go through all scripts on the page and look for 'data-entry'\n // We remember the name and measure the time between this script finished loading and\n // our mark 'sentry-tracing-init'\n if (global.document.scripts[i].dataset.entry === 'true') {\n entryScriptSrc = global.document.scripts[i].src;\n break;\n }\n }\n }\n\n let entryScriptStartTimestamp: number | undefined;\n let tracingInitMarkStartTime: number | undefined;\n let responseStartTimestamp: number | undefined;\n let requestStartTimestamp: number | undefined;\n\n global.performance\n .getEntries()\n .slice(this._performanceCursor)\n .forEach((entry: Record) => {\n const startTime = msToSec(entry.startTime as number);\n const duration = msToSec(entry.duration as number);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart as number);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart as number);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n const startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') {\n tracingInitMarkStartTime = startTimestamp;\n }\n\n // capture web vitals\n\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n logger.log('[Measurements] Adding FP');\n this._measurements['fp'] = { value: entry.startTime };\n this._measurements['mark.fp'] = { value: startTimestamp };\n }\n\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n logger.log('[Measurements] Adding FCP');\n this._measurements['fcp'] = { value: entry.startTime };\n this._measurements['mark.fcp'] = { value: startTimestamp };\n }\n\n break;\n }\n case 'resource': {\n const resourceName = (entry.name as string).replace(global.location.origin, '');\n const endTimestamp = addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n // We remember the entry script end time to calculate the difference to the first init mark\n if (entryScriptStartTimestamp === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) {\n entryScriptStartTimestamp = endTimestamp;\n }\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n if (entryScriptStartTimestamp !== undefined && tracingInitMarkStartTime !== undefined) {\n _startChild(transaction, {\n description: 'evaluation',\n endTimestamp: tracingInitMarkStartTime,\n op: 'script',\n startTimestamp: entryScriptStartTimestamp,\n });\n }\n\n this._performanceCursor = Math.max(performance.getEntries().length - 1, 0);\n\n this._trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // normalize applicable web vital values to be relative to transaction.startTimestamp\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n logger.log('[Measurements] Adding TTFB');\n this._measurements['ttfb'] = { value: (responseStartTimestamp - transaction.startTimestamp) * 1000 };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n this._measurements['ttfb.requestTime'] = { value: (responseStartTimestamp - requestStartTimestamp) * 1000 };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!this._measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n\n const oldValue = this._measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n\n const delta = normalizedValue - oldValue;\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n\n this._measurements[name].value = normalizedValue;\n });\n\n if (this._measurements['mark.fid'] && this._measurements['fid']) {\n // create span for FID\n\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: this._measurements['mark.fid'].value + msToSec(this._measurements['fid'].value),\n op: 'web.vitals',\n startTimestamp: this._measurements['mark.fid'].value,\n });\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in this._measurements)) {\n delete this._measurements.cls;\n }\n\n transaction.setMeasurements(this._measurements);\n this._tagMetricInfo(transaction);\n }\n }\n\n /** Add LCP / CLS data to transaction to allow debugging */\n private _tagMetricInfo(transaction: Transaction): void {\n if (this._lcpEntry) {\n logger.log('[Measurements] Adding LCP Data');\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (this._lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(this._lcpEntry.element));\n }\n\n if (this._lcpEntry.id) {\n transaction.setTag('lcp.id', this._lcpEntry.id);\n }\n\n if (this._lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', this._lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', this._lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (this._clsEntry && this._clsEntry.sources) {\n logger.log('[Measurements] Adding CLS Data');\n this._clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n }\n\n /** Starts tracking the Cumulative Layout Shift on the current page. */\n private _trackCLS(): void {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n getCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n logger.log('[Measurements] Adding CLS');\n this._measurements['cls'] = { value: metric.value };\n this._clsEntry = entry as LayoutShift;\n });\n }\n\n /**\n * Capture the information of the user agent.\n */\n private _trackNavigator(transaction: Transaction): void {\n const navigator = global.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n this._measurements['connection.rtt'] = { value: connection.rtt as number };\n }\n\n if (isMeasurementValue(connection.downlink)) {\n this._measurements['connection.downlink'] = { value: connection.downlink as number };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', String(navigator.deviceMemory));\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n }\n\n /** Starts tracking the Largest Contentful Paint on the current page. */\n private _trackLCP(reportAllChanges: boolean): void {\n getLCP(metric => {\n const entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime as number);\n logger.log('[Measurements] Adding LCP');\n this._measurements['lcp'] = { value: metric.value };\n this._measurements['mark.lcp'] = { value: timeOrigin + startTime };\n this._lcpEntry = entry as LargestContentfulPaint;\n }, reportAllChanges);\n }\n\n /** Starts tracking the First Input Delay on the current page. */\n private _trackFID(): void {\n getFID(metric => {\n const entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime as number);\n logger.log('[Measurements] Adding FID');\n this._measurements['fid'] = { value: metric.value };\n this._measurements['mark.fid'] = { value: timeOrigin + startTime };\n });\n }\n}\n\n/** Instrument navigation entries */\nfunction addNavigationSpans(transaction: Transaction, entry: Record, timeOrigin: number): void {\n addPerformanceNavigationTiming({ transaction, entry, event: 'unloadEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'redirect', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'domContentLoadedEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'loadEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'connect', timeOrigin });\n addPerformanceNavigationTiming({\n transaction,\n entry,\n event: 'secureConnection',\n timeOrigin,\n eventEnd: 'connectEnd',\n description: 'TLS/SSL',\n });\n addPerformanceNavigationTiming({\n transaction,\n entry,\n event: 'fetch',\n timeOrigin,\n eventEnd: 'domainLookupStart',\n description: 'cache',\n });\n addPerformanceNavigationTiming({ transaction, entry, event: 'domainLookup', timeOrigin, description: 'DNS' });\n addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create measure related spans */\nfunction addMeasureSpans(\n transaction: Transaction,\n entry: Record,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\nexport interface ResourceEntry extends Record {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n}\n\n/** Create resource-related spans */\nexport function addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceName: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number | undefined {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return undefined;\n }\n\n const data: Record = {};\n if ('transferSize' in entry) {\n data['Transfer Size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['Encoded Body Size'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['Decoded Body Size'] = entry.decodedBodySize;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource',\n startTimestamp,\n data,\n });\n\n return endTimestamp;\n}\n\n/** Create performance navigation related spans */\nfunction addPerformanceNavigationTiming(props: {\n transaction: Transaction;\n entry: Record;\n event: string;\n timeOrigin: number;\n eventEnd?: string;\n description?: string;\n}): void {\n const { transaction, entry, event, timeOrigin, eventEnd, description } = props;\n\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n description: description ?? event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\nfunction addRequest(transaction: Transaction, entry: Record, timeOrigin: number): void {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value: any): boolean {\n return typeof value === 'number' && isFinite(value);\n}\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { ReportHandler } from './types';\n\n// https://wicg.github.io/layout-instability/#sec-layout-shift\nexport interface LayoutShift extends PerformanceEntry {\n value: number;\n hadRecentInput: boolean;\n sources: Array;\n toJSON(): Record;\n}\n\nexport interface LayoutShiftAttribution {\n node?: Node;\n previousRect: DOMRectReadOnly;\n currentRect: DOMRectReadOnly;\n}\n\nexport const getCLS = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n const entryHandler = (entry: LayoutShift): void => {\n // Only count layout shifts without recent user input.\n // TODO: Figure out why entry can be undefined\n if (entry && !entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n };\n\n const po = observe('layout-shift', entryHandler as PerformanceEntryHandler);\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n\n onHidden(() => {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n report(true);\n });\n }\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { PerformanceEventTiming, ReportHandler } from './types';\n\nexport const getFID = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n let report: ReturnType;\n\n const entryHandler = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (report && entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const po = observe('first-input', entryHandler as PerformanceEntryHandler);\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n onHidden(() => {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n po.disconnect();\n }, true);\n }\n};\n", "import { addInstrumentationHandler, isInstanceOf, isMatchingPattern } from '@sentry/utils';\n\nimport { Span } from '../span';\nimport { SpanStatus } from '../spanstatus';\nimport { getActiveTransaction, hasTracingEnabled } from '../utils';\n\nexport const DEFAULT_TRACING_ORIGINS = ['localhost', /^\\//];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * List of strings / regex where the integration should create Spans out of. Additionally this will be used\n * to define which outgoing requests the `sentry-trace` header will be attached to.\n *\n * Default: ['localhost', /^\\//] {@see DEFAULT_TRACING_ORIGINS}\n */\n tracingOrigins: Array;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * By default it uses the `tracingOrigins` options as a url match.\n */\n shouldCreateSpanForRequest?(url: string): boolean;\n}\n\n/** Data returned from fetch callback */\nexport interface FetchData {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[]; // the arguments passed to the fetch call itself\n fetchData?: {\n method: string;\n url: string;\n // span_id\n __span?: string;\n };\n\n // TODO Should this be unknown instead? If we vendor types, make it a Response\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response?: any;\n error?: unknown;\n\n startTimestamp: number;\n endTimestamp?: number;\n}\n\n/** Data returned from XHR request */\nexport interface XHRData {\n xhr?: {\n __sentry_xhr__?: {\n method: string;\n url: string;\n status_code: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: Record;\n };\n __sentry_xhr_span_id__?: string;\n setRequestHeader?: (key: string, val: string) => void;\n __sentry_own_request__?: boolean;\n };\n startTimestamp: number;\n endTimestamp?: number;\n}\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n tracingOrigins: DEFAULT_TRACING_ORIGINS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest } = {\n ...defaultRequestInstrumentationOptions,\n ..._options,\n };\n\n // We should cache url -> decision so that we don't have to compute\n // regexp everytime we create a request.\n const urlMap: Record = {};\n\n const defaultShouldCreateSpan = (url: string): boolean => {\n if (urlMap[url]) {\n return urlMap[url];\n }\n const origins = tracingOrigins;\n urlMap[url] =\n origins.some((origin: string | RegExp) => isMatchingPattern(url, origin)) &&\n !isMatchingPattern(url, 'sentry_key');\n return urlMap[url];\n };\n\n // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves\n // That's why we filter out already unwanted Spans from tracingOrigins\n let shouldCreateSpan = defaultShouldCreateSpan;\n if (typeof shouldCreateSpanForRequest === 'function') {\n shouldCreateSpan = (url: string) => {\n return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url);\n };\n }\n\n const spans: Record = {};\n\n if (traceFetch) {\n addInstrumentationHandler({\n callback: (handlerData: FetchData) => {\n fetchCallback(handlerData, shouldCreateSpan, spans);\n },\n type: 'fetch',\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler({\n callback: (handlerData: XHRData) => {\n xhrCallback(handlerData, shouldCreateSpan, spans);\n },\n type: 'xhr',\n });\n }\n}\n\n/**\n * Create and track fetch request spans\n */\nexport function fetchCallback(\n handlerData: FetchData,\n shouldCreateSpan: (url: string) => boolean,\n spans: Record,\n): void {\n if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp && handlerData.fetchData.__span) {\n const span = spans[handlerData.fetchData.__span];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n } else if (handlerData.error) {\n span.setStatus(SpanStatus.InternalError);\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[handlerData.fetchData.__span];\n }\n return;\n }\n\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const span = activeTransaction.startChild({\n data: {\n ...handlerData.fetchData,\n type: 'fetch',\n },\n description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`,\n op: 'http.client',\n });\n\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n\n const request = (handlerData.args[0] = handlerData.args[0] as string | Request);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options = (handlerData.args[1] = (handlerData.args[1] as { [key: string]: any }) || {});\n let headers = options.headers;\n if (isInstanceOf(request, Request)) {\n headers = (request as Request).headers;\n }\n if (headers) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (typeof headers.append === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n headers.append('sentry-trace', span.toTraceparent());\n } else if (Array.isArray(headers)) {\n headers = [...headers, ['sentry-trace', span.toTraceparent()]];\n } else {\n headers = { ...headers, 'sentry-trace': span.toTraceparent() };\n }\n } else {\n headers = { 'sentry-trace': span.toTraceparent() };\n }\n options.headers = headers;\n }\n}\n\n/**\n * Create and track xhr request spans\n */\nexport function xhrCallback(\n handlerData: XHRData,\n shouldCreateSpan: (url: string) => boolean,\n spans: Record,\n): void {\n if (\n !hasTracingEnabled() ||\n handlerData.xhr?.__sentry_own_request__ ||\n !(handlerData.xhr?.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))\n ) {\n return;\n }\n\n const xhr = handlerData.xhr.__sentry_xhr__;\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) {\n const span = spans[handlerData.xhr.__sentry_xhr_span_id__];\n if (span) {\n span.setHttpStatus(xhr.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[handlerData.xhr.__sentry_xhr_span_id__];\n }\n return;\n }\n\n // if not, create a new span to track it\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const span = activeTransaction.startChild({\n data: {\n ...xhr.data,\n type: 'xhr',\n method: xhr.method,\n url: xhr.url,\n },\n description: `${xhr.method} ${xhr.url}`,\n op: 'http.client',\n });\n\n handlerData.xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[handlerData.xhr.__sentry_xhr_span_id__] = span;\n\n if (handlerData.xhr.setRequestHeader) {\n try {\n handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}\n", "import { Transaction, TransactionContext } from '@sentry/types';\nimport { addInstrumentationHandler, getGlobalObject, logger } from '@sentry/utils';\n\nconst global = getGlobalObject();\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!global || !global.location) {\n logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = global.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({ name: global.location.pathname, op: 'pageload' });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler({\n callback: ({ to, from }: { to: string; from?: string }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({ name: global.location.pathname, op: 'navigation' });\n }\n },\n type: 'history',\n });\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration, Transaction, TransactionContext } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\n\nimport { startIdleTransaction } from '../hubextensions';\nimport { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction';\nimport { SpanStatus } from '../spanstatus';\nimport { extractTraceparentData, secToMs } from '../utils';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { DEFAULT_METRICS_INSTR_OPTIONS, MetricsInstrumentation, MetricsInstrumentationOptions } from './metrics';\nimport {\n defaultRequestInstrumentationOptions,\n instrumentOutgoingRequests,\n RequestInstrumentationOptions,\n} from './request';\nimport { instrumentRoutingWithDefaults } from './router';\n\nexport const DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600;\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished. The transaction will use the end timestamp of\n * the last finished span as the endtime for the transaction.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * The maximum duration of a transaction before it will be marked as \"deadline_exceeded\".\n * If you never want to mark a transaction set it to 0.\n * Time is in seconds.\n *\n * Default: 600\n */\n maxTransactionDuration: number;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n idleTimeout: DEFAULT_IDLE_TIMEOUT,\n markBackgroundTransactions: true,\n maxTransactionDuration: DEFAULT_MAX_TRANSACTION_DURATION_SECONDS,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nexport class BrowserTracing implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'BrowserTracing';\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string = BrowserTracing.id;\n\n private _getCurrentHub?: () => Hub;\n\n private readonly _metrics: MetricsInstrumentation;\n\n private readonly _emitOptionsWarning: boolean = false;\n\n public constructor(_options?: Partial) {\n let tracingOrigins = defaultRequestInstrumentationOptions.tracingOrigins;\n // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances\n if (\n _options &&\n _options.tracingOrigins &&\n Array.isArray(_options.tracingOrigins) &&\n _options.tracingOrigins.length !== 0\n ) {\n tracingOrigins = _options.tracingOrigins;\n } else {\n this._emitOptionsWarning = true;\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n tracingOrigins,\n };\n\n this._metrics = new MetricsInstrumentation({ ...DEFAULT_METRICS_INSTR_OPTIONS, ...this.options._metricOptions });\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n\n if (this._emitOptionsWarning) {\n logger.warn(\n '[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.',\n );\n logger.warn(\n `[Tracing] We added a reasonable default for you: ${defaultRequestInstrumentationOptions.tracingOrigins}`,\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n tracingOrigins,\n shouldCreateSpanForRequest,\n } = this.options;\n\n instrumentRouting(\n (context: TransactionContext) => this._createRouteTransaction(context),\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n instrumentOutgoingRequests({ traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeNavigate, idleTimeout, maxTransactionDuration } = this.options;\n\n const parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined;\n\n const expandedContext = {\n ...context,\n ...parentContextFromHeader,\n trimEnd: true,\n };\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n if (finalContext.sampled === false) {\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const hub = this._getCurrentHub();\n const { location } = getGlobalObject() as WindowOrWorkerGlobalScope & { location: Location };\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n true,\n { location }, // for use in the tracesSampler\n );\n idleTransaction.registerBeforeFinishCallback((transaction, endTimestamp) => {\n this._metrics.addPerformanceEntries(transaction);\n adjustTransactionDuration(secToMs(maxTransactionDuration), transaction, endTimestamp);\n });\n\n return idleTransaction as Transaction;\n }\n}\n\n/**\n * Gets transaction context from a sentry-trace meta.\n *\n * @returns Transaction context data from the header or undefined if there's no header or the header is malformed\n */\nexport function getHeaderContext(): Partial | undefined {\n const header = getMetaContent('sentry-trace');\n if (header) {\n return extractTraceparentData(header);\n }\n\n return undefined;\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | null {\n const el = getGlobalObject().document.querySelector(`meta[name=${metaName}]`);\n return el ? el.getAttribute('content') : null;\n}\n\n/** Adjusts transaction value based on max transaction duration */\nfunction adjustTransactionDuration(maxDuration: number, transaction: IdleTransaction, endTimestamp: number): void {\n const diff = endTimestamp - transaction.startTimestamp;\n const isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0);\n if (isOutdatedTransaction) {\n transaction.setStatus(SpanStatus.DeadlineExceeded);\n transaction.setTag('maxTransactionDurationExceeded', 'true');\n }\n}\n", "export {\n Breadcrumb,\n Request,\n SdkInfo,\n Event,\n Exception,\n Response,\n Severity,\n StackFrame,\n Stacktrace,\n Status,\n Thread,\n User,\n} from '@sentry/types';\n\nexport {\n addGlobalEventProcessor,\n addBreadcrumb,\n captureException,\n captureEvent,\n captureMessage,\n configureScope,\n getHubFromCarrier,\n getCurrentHub,\n Hub,\n Scope,\n setContext,\n setExtra,\n setExtras,\n setTag,\n setTags,\n setUser,\n startTransaction,\n Transports,\n withScope,\n} from '@sentry/browser';\n\nexport { BrowserOptions } from '@sentry/browser';\nexport { BrowserClient, ReportDialogOptions } from '@sentry/browser';\nexport {\n defaultIntegrations,\n forceLoad,\n init,\n lastEventId,\n onLoad,\n showReportDialog,\n flush,\n close,\n wrap,\n} from '@sentry/browser';\nexport { SDK_NAME, SDK_VERSION } from '@sentry/browser';\n\nimport { Integrations as BrowserIntegrations } from '@sentry/browser';\nimport { getGlobalObject } from '@sentry/utils';\n\nimport { BrowserTracing } from './browser';\nimport { addExtensionMethods } from './hubextensions';\n\nexport { Span } from './span';\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 ...BrowserIntegrations,\n BrowserTracing,\n};\n\nexport { INTEGRATIONS as Integrations };\n\n// We are patching the global object with our hub extension methods\naddExtensionMethods();\n\nexport { addExtensionMethods };\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 hub.getScope()?.update(options.initialScope);\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n" ], "names": [ "LogLevel", "SessionStatus", "RequestSessionStatus", "Severity", "Status", "TransactionSamplingMethod", "Outcome", "isError", "wat", "Object", "prototype", "toString", "call", "isInstanceOf", "Error", "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", "level", "Debug", "Info", "Warning", "Fatal", "Critical", "Log", "code", "Success", "RateLimit", "Invalid", "Failed", "Unknown", "setPrototypeOf", "__proto__", "Array", "obj", "proto", "prop", "hasOwnProperty", "message", "_super", "_this", "name", "_newTarget", "constructor", "__extends", "DSN_REGEX", "from", "this", "_fromString", "_fromComponents", "_validate", "Dsn", "withPassword", "_a", "host", "path", "pass", "port", "projectId", "str", "match", "exec", "SentryError", "protocol", "publicKey", "_b", "_c", "slice", "pop", "projectMatch", "components", "user", "component", "ERROR_MESSAGE", "isNaN", "parseInt", "isNodeEnv", "process", "dynamicRequire", "mod", "request", "require", "truncate", "max", "substr", "safeJoin", "input", "delimiter", "isArray", "output", "value", "String", "e", "isMatchingPattern", "pattern", "test", "indexOf", "fallbackGlobalObject", "getGlobalObject", "global", "window", "self", "uuid4", "crypto", "msCrypto", "getRandomValues", "arr", "Uint16Array", "pad", "num", "v", "replace", "c", "r", "Math", "random", "parseUrl", "url", "query", "fragment", "relative", "getEventDescription", "event", "exception", "values", "type", "event_id", "consoleSandbox", "callback", "originalConsole", "console", "wrappedLevels", "__sentry_original__", "result", "keys", "addExceptionTypeValue", "addExceptionMechanism", "mechanism", "defaultRetryAfter", "PREFIX", "_enabled", "Logger", "_i", "args", "log", "warn", "error", "__SENTRY__", "logger", "_hasWeakSet", "WeakSet", "_inner", "Memo", "has", "add", "delete", "splice", "defaultFunctionName", "getFunctionName", "fn", "fill", "source", "replacementFactory", "original", "wrapped", "defineProperties", "enumerable", "_Oo", "getWalkSource", "err", "stack", "event_1", "target", "currentTarget", "CustomEvent", "detail", "jsonSize", "encodeURI", "utf8Length", "JSON", "stringify", "normalizeToSize", "object", "depth", "maxSize", "serialized", "normalize", "normalizeValue", "_events", "document", "walk", "memo", "Infinity", "normalized", "serializeValue", "toJSON", "acc", "memoize", "innerKey", "unmemoize", "parse", "extractExceptionKeysForMessage", "maxLength", "sort", "includedKeys", "dropUndefinedKeys", "val", "rv", "__values", "supportsFetch", "Headers", "Request", "Response", "isNativeFetch", "func", "supportsReferrerPolicy", "referrerPolicy", "lastHref", "handlers", "instrumented", "instrument", "originalConsoleLevel", "triggerHandlers", "Function", "apply", "instrumentConsole", "triggerDOMHandler", "bind", "globalDOMEventHandler", "makeDOMEventHandler", "addEventListener", "originalAddEventListener", "listener", "options", "handlers_1", "__sentry_instrumentation_handlers__", "handlerForType", "refCount", "handler", "originalRemoveEventListener", "handlers_2", "undefined", "instrumentDOM", "requestKeys", "requestValues", "xhrproto", "XMLHttpRequest", "originalOpen", "xhr", "__sentry_xhr__", "method", "toUpperCase", "__sentry_own_request__", "onreadystatechangeHandler", "readyState", "status_code", "status", "requestPos", "args_1", "body", "endTimestamp", "Date", "now", "startTimestamp", "onreadystatechange", "readyStateArgs", "originalSend", "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", "oldOnPopState", "onpopstate", "historyReplacementFunction", "originalHistoryFunction", "to", "location", "href", "instrumentHistory", "_oldOnErrorHandler", "onerror", "msg", "line", "column", "arguments", "_oldOnUnhandledRejectionHandler", "onunhandledrejection", "addInstrumentationHandler", "data", "fetchArgs", "debounceTimerID", "lastCapturedEvent", "debounceDuration", "globalListener", "isContentEditable", "shouldSkipDOMEvent", "previous", "current", "shouldShortcircuitPreviousDebounce", "clearTimeout", "setTimeout", "States", "executor", "PENDING", "_setResult", "RESOLVED", "reason", "REJECTED", "state", "_state", "_resolve", "_reject", "_value", "_executeHandlers", "_handlers", "concat", "cachedHandlers", "done", "onfulfilled", "onrejected", "SyncPromise", "resolve", "_", "reject", "collection", "counter", "resolvedCollection", "item", "index", "TypeError", "_attachHandler", "onfinally", "isRejected", "_limit", "PromiseBuffer", "taskProducer", "isReady", "task", "_buffer", "remove", "timeout", "capturedSetTimeout", "all", "dateTimestampSource", "nowSeconds", "platformPerformance", "module", "performance", "getNodePerformance", "timeOrigin", "getBrowserPerformance", "timestampSource", "dateTimestampInSeconds", "timestampInSeconds", "timestampWithMs", "browserPerformanceTimeOrigin", "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", "spanRecorder", "spans", "session", "captureContext", "updatedScope", "contexts", "breadcrumb", "maxBreadcrumbs", "maxCrumbs", "min", "mergedBreadcrumb", "timestamp", "__spread", "hint", "trace", "getTraceContext", "transactionName", "_applyFingerprint", "breadcrumbs", "_notifyEventProcessors", "getGlobalEventProcessors", "processors", "processor", "final", "_notifyingListeners", "globalEventProcessors", "addGlobalEventProcessor", "Ok", "startingTime", "started", "Session", "ipAddress", "ip_address", "did", "email", "username", "ignoreDuration", "sid", "init", "duration", "release", "environment", "userAgent", "errors", "Exited", "toISOString", "attrs", "user_agent", "API_VERSION", "client", "_version", "getStackTop", "bindClient", "Hub", "version", "setupIntegrations", "clone", "getScope", "getStack", "getClient", "pushScope", "popScope", "_stack", "eventId", "_lastEventId", "finalHint", "syntheticException", "originalException", "_invokeClient", "beforeBreadcrumb", "_d", "finalBreadcrumb", "addBreadcrumb", "setUser", "setTags", "setExtras", "setTag", "setExtra", "setContext", "oldHub", "makeMain", "integration", "getIntegration", "_callExtensionMethod", "customSamplingContext", "endSession", "_sendSessionUpdate", "getSession", "close", "setSession", "getUser", "currentSession", "captureSession", "sentry", "getMainCarrier", "extensions", "carrier", "hub", "registry", "getHubFromCarrier", "setHubOnCarrier", "getCurrentHub", "hasHubOnCarrier", "isOlderThan", "activeDomain", "domain", "active", "registryHubTopStack", "getHubFromActiveDomain", "callOnHub", "captureException", "withScope", "dsn", "metadata", "tunnel", "_dsnObject", "_tunnel", "API", "getDsn", "_getIngestEndpoint", "getStoreEndpoint", "_encodedAuth", "forceEnvelope", "_getEnvelopeEndpoint", "clientName", "clientVersion", "header", "Content-Type", "X-Sentry-Auth", "dialogOptions", "endpoint", "getBaseApiEndpoint", "encodedOptions", "encodeURIComponent", "auth", "sentry_key", "sentry_version", "installedIntegrations", "filterDuplicates", "integrations", "reduce", "every", "accIntegration", "defaultIntegrations", "userIntegrations", "userIntegration", "integrationsNames", "getIntegrationsToSetup", "setupOnce", "setupIntegration", "defineProperty", "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", "handled", "sessionNonTerminal", "Crashed", "Number", "sendSession", "ticked", "interval", "setInterval", "_numProcessing", "clearInterval", "normalizeDepth", "prepared", "_applyClientOptions", "_applyIntegrationsMetadata", "finalScope", "applyToEvent", "evt", "_normalizeEvent", "b", "ensureNoCircularStructures", "dist", "maxValueLength", "integrationsArray", "sdk", "sendEvent", "_processEvent", "finalEvent", "beforeSend", "sampleRate", "transport", "isTransaction", "recordLostEvent", "SampleRate", "_prepareEvent", "EventProcessor", "__sentry__", "beforeSendResult", "_ensureBeforeSendRv", "processedEvent", "BeforeSend", "_updateSessionFromEvent", "_sendEvent", "promise", "nullErr", "NoopTransport", "Skipped", "_transport", "_setupTransport", "BaseBackend", "_exception", "_hint", "_message", "getSdkMetadataForEnvelopeHeader", "api", "enhanceEventWithSdkInfo", "sdkInfo", "packages", "sessionToSentryRequest", "sent_at", "getEnvelopeEndpointWithUrlEncodedAuth", "eventToSentryRequest", "eventType", "useEnvelope", "transactionSampling", "samplingMethod", "debug_meta", "req", "getStoreEndpointWithUrlEncodedAuth", "envelope", "sample_rates", "rate", "originalFunctionToString", "SDK_VERSION", "FunctionToString", "DEFAULT_IGNORE_ERRORS", "InboundFilters", "clientOptions", "_mergeOptions", "_shouldDropEvent", "_isSentryError", "_isIgnoredError", "_isDeniedUrl", "_getEventFilterUrl", "_isAllowedUrl", "ignoreInternal", "ignoreErrors", "_getPossibleEventMessages", "some", "denyUrls", "allowUrls", "whitelistUrls", "blacklistUrls", "oO", "frames", "frame", "filename", "stacktrace", "frames_1", "_getLastValidUrl", "frames_2", "UNKNOWN_FUNCTION", "gecko", "winjs", "geckoEval", "chromeEval", "reactMinifiedRegexp", "computeStackTrace", "ex", "popSize", "framesToPop", "parts", "opera10Regex", "opera11Regex", "lines", "element", "extractMessage", "computeStackTraceFromStacktraceProp", "popFrames", "submatch", "isNative", "columnNumber", "computeStackTraceFromStackProp", "failed", "extractSafariExtensionDetails", "isSafariExtension", "isSafariWebExtension", "STACKTRACE_LIMIT", "exceptionFromStacktrace", "prepareFramesForEvent", "eventFromStacktrace", "localStack", "firstFrameFunction", "lastFrameFunction", "colno", "function", "in_app", "lineno", "eventFromUnknownInput", "domException", "name_1", "eventFromString", "DOMException.code", "rejection", "__serialized__", "eventFromPlainObject", "synthetic", "attachStacktrace", "cachedFetchImpl", "getNativeFetchImplementation", "fetchImpl", "sendReport", "navigator", "sendBeacon", "fetch_1", "credentials", "keepalive", "CATEGORY_MAPPING", "attachment", "_api", "_metadata", "sendClientReports", "visibilityState", "_flushOutcomes", "BaseTransport", "drain", "category", "_outcomes", "outcomes", "discarded_events", "quantity", "requestType", "headers", "fromHttpCode", "_handleRateLimit", "_disabledUntil", "_rateLimits", "rlHeader", "raHeader", "trim", "parameters", "headerDelay", "delay", "headerDate", "parseRetryAfterHeader", "_fetch", "FetchTransport", "_sendRequest", "sentryRequest", "originalPayload", "_isRateLimited", "RateLimitBackoff", "Promise", "fetchParameters", "assign", "x-sentry-rate-limits", "get", "retry-after", "_handleResponse", "catch", "QueueOverflow", "NetworkError", "XHRTransport", "getResponseHeader", "open", "setRequestHeader", "send", "BrowserBackend", "transportOptions", "Ut", "ignoreOnError", "shouldIgnoreOnError", "wrap", "before", "__sentry_wrapped__", "sentryWrapped", "wrappedArguments", "arg", "handleEvent", "addEventProcessor", "property", "getOwnPropertyDescriptor", "configurable", "GlobalHandlers", "stackTraceLimit", "_installGlobalOnErrorHandler", "_installGlobalOnUnhandledRejectionHandler", "_onErrorHandlerInstalled", "currentHub", "hasIntegration", "isFailedOwnDelivery", "_eventFromIncompleteOnError", "_enhanceEventWithInitialFrame", "captureEvent", "_onUnhandledRejectionHandlerInstalled", "_eventFromRejectionWithPrimitive", "groups", "getLocationHref", "DEFAULT_EVENT_TARGET", "TryCatch", "eventTarget", "requestAnimationFrame", "_wrapTimeFunction", "_wrapRAF", "_wrapXHR", "_wrapEventTarget", "originalCallback", "eventName", "wrappedEventHandler", "originalEventHandler", "wrapOptions", "Breadcrumbs", "dom", "_consoleBreadcrumb", "_domBreadcrumb", "_xhrBreadcrumb", "_fetchBreadcrumb", "_historyBreadcrumb", "fromString", "serializeAttribute", "parsedLoc", "parsedFrom", "parsedTo", "DEFAULT_KEY", "DEFAULT_LIMIT", "LinkedErrors", "_key", "limit", "_handler", "linkedErrors", "_walkErrorTree", "UserAgent", "referrer", "Referer", "User-Agent", "Dedupe", "currentEvent", "_previousEvent", "previousEvent", "_isSameMessageEvent", "_isSameExceptionEvent", "currentMessage", "previousMessage", "_isSameFingerprint", "_isSameStacktrace", "currentFrames", "_getFramesFromEvent", "previousFrames", "frameA", "frameB", "previousException", "_getExceptionFromEvent", "currentException", "currentFingerprint", "previousFingerprint", "BrowserClient", "script", "async", "src", "getReportDialogEndpoint", "onLoad", "onload", "injectionPoint", "injectReportDialog", "platform", "addSentryBreadcrumb", "CoreIntegrations.InboundFilters", "CoreIntegrations.FunctionToString", "windowIntegrations", "_window", "Sentry", "Integrations", "SpanStatus", "INTEGRATIONS", "CoreIntegrations", "BrowserIntegrations", "httpStatus", "Unauthenticated", "PermissionDenied", "NotFound", "AlreadyExists", "FailedPrecondition", "ResourceExhausted", "InvalidArgument", "Unimplemented", "Unavailable", "DeadlineExceeded", "InternalError", "UnknownError", "TRACEPARENT_REGEXP", "RegExp", "hasTracingEnabled", "getActiveTransaction", "getTransaction", "msToSec", "time", "errorCallback", "activeTransaction", "setStatus", "maxlen", "_maxlen", "SpanRecorder", "spanContext", "substring", "traceId", "spanId", "parentSpanId", "sampled", "op", "description", "Span", "startChild", "childSpan", "spanStatus", "sampledString", "parent_span_id", "span_id", "trace_id", "start_timestamp", "transactionContext", "_hub", "_trimEnd", "trimEnd", "Transaction", "measurements", "_measurements", "newMetadata", "finish", "finishedSpans", "s", "prev", "toContext", "updateWithContext", "SpanClass", "DEFAULT_IDLE_TIMEOUT", "_pushActivity", "_popActivity", "transactionSpanId", "IdleTransactionSpanRecorder", "_idleHub", "_idleTimeout", "_onScope", "clearActiveTransaction", "configureScope", "setSpan", "_initTimeout", "_finished", "IdleTransaction", "activities", "_beforeFinishCallbacks", "Cancelled", "keepSpan", "_pingHeartbeat", "end_1", "heartbeatString", "_prevHeartbeatString", "_heartbeatCounter", "_beat", "traceHeaders", "sentry-trace", "toTraceparent", "sample", "samplingContext", "setMetadata", "Explicit", "tracesSampler", "Sampler", "parentSampled", "Inheritance", "tracesSampleRate", "Rate", "isValidSampleRate", "_startTransaction", "initSpanRecorder", "_experiments", "maxSpans", "_autoloadDatabaseIntegrations", "packageToIntegrationMapping", "mongodb", "Mongo", "mongoose", "mysql", "Mysql", "pg", "Postgres", "mappedPackages", "moduleName", "cwd", "loadModule", "pkg", "p", "addExtensionMethods", "startTransaction", "bindReporter", "metric", "reportAllChanges", "prevValue", "forceReport", "delta", "initMetric", "entries", "floor", "observe", "PerformanceObserver", "supportedEntryTypes", "includes", "po", "l", "getEntries", "buffered", "onHidden", "cb", "once", "onHiddenOrPageHide", "removeEventListener", "firstHiddenTime", "getVisibilityWatcher", "timeStamp", "reportedMetricIDs", "DEFAULT_METRICS_INSTR_OPTIONS", "Ln", "mark", "_trackCLS", "_trackLCP", "_reportAllChanges", "_trackFID", "MetricsInstrumentation", "entryScriptSrc", "entryScriptStartTimestamp", "tracingInitMarkStartTime", "responseStartTimestamp", "requestStartTimestamp", "scripts", "dataset", "entry", "_performanceCursor", "startTime", "entryType", "addPerformanceNavigationTiming", "eventEnd", "_startChild", "requestStart", "responseEnd", "responseStart", "addRequest", "addNavigationSpans", "measureStartTimestamp", "measureEndTimestamp", "addMeasureSpans", "firstHidden", "shouldRecord", "resourceName", "origin", "initiatorType", "transferSize", "encodedBodySize", "decodedBodySize", "addResourceSpans", "_trackNavigator", "timeOrigin_1", "oldValue", "measurementTimestamp", "normalizedValue", "cls", "setMeasurements", "_tagMetricInfo", "_lcpEntry", "size", "_clsEntry", "sources", "node", "onReport", "report", "sessionValue", "sessionEntries", "entryHandler", "hadRecentInput", "firstSessionEntry", "lastSessionEntry", "takeRecords", "connection", "effectiveType", "isMeasurementValue", "rtt", "downlink", "deviceMemory", "hardwareConcurrency", "visibilityWatcher", "stopListening_1", "disconnect", "capture", "getLCP", "processingStart", "props", "end", "start", "ctx", "isFinite", "defaultRequestInstrumentationOptions", "traceFetch", "traceXHR", "tracingOrigins", "instrumentOutgoingRequests", "shouldCreateSpanForRequest", "urlMap", "defaultShouldCreateSpan", "origins", "shouldCreateSpan", "__span", "setHttpStatus", "append", "fetchCallback", "__sentry_xhr_span_id__", "xhrCallback", "DEFAULT_BROWSER_TRACING_OPTIONS", "idleTimeout", "markBackgroundTransactions", "maxTransactionDuration", "routingInstrumentation", "customStartTransaction", "startTransactionOnPageLoad", "startTransactionOnLocationChange", "startingUrl", "pathname", "BrowserTracing", "_emitOptionsWarning", "_metrics", "_metricOptions", "_getCurrentHub", "instrumentRouting", "_createRouteTransaction", "beforeNavigate", "parentContextFromHeader", "metaName", "querySelector", "traceparent", "matches", "extractTraceparentData", "getHeaderContext", "expandedContext", "modifiedContext", "finalContext", "idleTransaction", "onScope", "startIdleTransaction", "registerBeforeFinishCallback", "addPerformanceEntries", "maxDuration", "diff", "adjustTransactionDuration", "window_1", "SENTRY_RELEASE", "autoSessionTracking", "clientClass", "debug", "enable", "initialScope", "initAndBind", "startSession", "startSessionTracking", "lastEventId", "showReportDialog", "internalWrap" ], "mappings": ";gVACYA,EC2DAC,EAWAC,ECrEAC,ECAAC,ECqH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