@sentry/utils

  • Version 7.71.0
  • Published
  • 1.12 MB
  • 2 dependencies
  • MIT license

Install

npm i @sentry/utils
yarn add @sentry/utils
pnpm add @sentry/utils

Overview

Utilities for all Sentry JavaScript SDKs

Index

Variables

Functions

Classes

Interfaces

Type Aliases

Variables

variable BAGGAGE_HEADER_NAME

const BAGGAGE_HEADER_NAME: string;

    variable browserPerformanceTimeOrigin

    const browserPerformanceTimeOrigin: number;
    • The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the performance API is available.

    variable CONSOLE_LEVELS

    const CONSOLE_LEVELS: readonly [
    'debug',
    'info',
    'warn',
    'error',
    'log',
    'assert',
    'trace'
    ];

      variable DEFAULT_RETRY_AFTER

      const DEFAULT_RETRY_AFTER: number;

        variable GLOBAL_OBJ

        const GLOBAL_OBJ: InternalGlobal;
        • Get's the global object for the current JavaScript runtime

        variable logger

        const logger: Logger;

          variable MAX_BAGGAGE_STRING_LENGTH

          const MAX_BAGGAGE_STRING_LENGTH: number;
          • Max length of a serialized baggage string

            https://www.w3.org/TR/baggage/#limits

          variable originalConsoleMethods

          const originalConsoleMethods: {
          debug?: (...args: any[]) => void;
          info?: (...args: any[]) => void;
          warn?: (...args: any[]) => void;
          error?: (...args: any[]) => void;
          log?: (...args: any[]) => void;
          assert?: (...args: any[]) => void;
          trace?: (...args: any[]) => void;
          };
          • This may be mutated by the console instrumentation.

          variable SENTRY_BAGGAGE_KEY_PREFIX

          const SENTRY_BAGGAGE_KEY_PREFIX: string;

            variable SENTRY_BAGGAGE_KEY_PREFIX_REGEX

            const SENTRY_BAGGAGE_KEY_PREFIX_REGEX: RegExp;

              variable SENTRY_XHR_DATA_KEY

              const SENTRY_XHR_DATA_KEY: string;

                variable TRACEPARENT_REGEXP

                const TRACEPARENT_REGEXP: RegExp;

                  variable usingPerformanceAPI

                  const usingPerformanceAPI: boolean;
                  • A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.

                  variable validSeverityLevels

                  const validSeverityLevels: string[];

                    Functions

                    function addContextToFrame

                    addContextToFrame: (
                    lines: string[],
                    frame: StackFrame,
                    linesOfContext?: number
                    ) => void;
                    • This function adds context (pre/post/line) lines to the provided frame

                      Parameter lines

                      string[] containing all lines

                      Parameter frame

                      StackFrame that will be mutated

                      Parameter linesOfContext

                      number of context lines we want to add pre/post

                    function addExceptionMechanism

                    addExceptionMechanism: (event: Event, newMechanism?: Mechanism) => void;
                    • Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.

                      Parameter event

                      The event to modify.

                      Parameter newMechanism

                      Mechanism data to add to the event.

                    function addExceptionTypeValue

                    addExceptionTypeValue: (event: Event, value?: string, type?: string) => void;
                    • Adds exception values, type and value to an synthetic Exception.

                      Parameter event

                      The event to modify.

                      Parameter value

                      Value of the exception.

                      Parameter type

                      Type of the exception.

                    function addInstrumentationHandler

                    addInstrumentationHandler: (
                    type: InstrumentHandlerType,
                    callback: InstrumentHandlerCallback
                    ) => void;
                    • Add handler that will be called when given type of instrumentation triggers. Use at your own risk, this might break without changelog notice, only used internally.

                    function addItemToEnvelope

                    addItemToEnvelope: <E extends Envelope>(envelope: E, newItem: E[1][number]) => E;
                    • Add an item to an envelope. Make sure to always explicitly provide the generic to this function so that the envelope types resolve correctly.

                    function addNonEnumerableProperty

                    addNonEnumerableProperty: (
                    obj: { [key: string]: unknown },
                    name: string,
                    value: unknown
                    ) => void;
                    • Defines a non-enumerable property on the given object.

                      Parameter obj

                      The object on which to set the property

                      Parameter name

                      The name of the property to be set

                      Parameter value

                      The value to which to set the property

                    function addOrUpdateIntegration

                    addOrUpdateIntegration: <T extends UserIntegrations>(
                    defaultIntegrationInstance: Integration,
                    userIntegrations: T,
                    forcedOptions?: ForcedIntegrationOptions
                    ) => T;
                    • Enforces inclusion of a given integration with specified options in an integration array originally determined by the user, by either including the given default instance or by patching an existing user instance with the given options.

                      Ideally this would happen when integrations are set up, but there isn't currently a mechanism there for merging options from a default integration instance with those from a user-provided instance of the same integration, only for allowing the user to override a default instance entirely. (TODO: Fix that.)

                      Parameter defaultIntegrationInstance

                      An instance of the integration with the correct options already set

                      Parameter userIntegrations

                      Integrations defined by the user.

                      Parameter forcedOptions

                      Options with which to patch an existing user-derived instance on the integration.

                      Returns

                      A final integrations array.

                    function addRequestDataToEvent

                    addRequestDataToEvent: (
                    event: Event,
                    req: PolymorphicRequest,
                    options?: AddRequestDataToEventOptions
                    ) => Event;
                    • Add data from the given request to the given event

                      Parameter event

                      The event to which the request data will be added

                      Parameter req

                      Request object

                      Parameter

                      options.include Flags to control what data is included

                      Parameter

                      options.deps Injected platform-specific dependencies

                    function addRequestDataToTransaction

                    addRequestDataToTransaction: (
                    transaction: Transaction | undefined,
                    req: PolymorphicRequest,
                    deps?: InjectedNodeDeps
                    ) => void;
                    • Sets parameterized route as transaction name e.g.: GET /users/:id Also adds more context data on the transaction from the request

                    function applyAggregateErrorsToEvent

                    applyAggregateErrorsToEvent: (
                    exceptionFromErrorImplementation: (
                    stackParser: StackParser,
                    ex: Error
                    ) => Exception,
                    parser: StackParser,
                    maxValueLimit: number | undefined,
                    key: string,
                    limit: number,
                    event: Event,
                    hint?: EventHint
                    ) => void;
                    • Creates exceptions inside event.exception.values for errors that are nested on properties based on the key parameter.

                    function arrayify

                    arrayify: <T = unknown>(maybeArray: T | T[]) => T[];
                    • Checks whether the given input is already an array, and if it isn't, wraps it in one.

                      Parameter maybeArray

                      Input to turn into an array, if necessary

                      Returns

                      The input, if already an array, or an array with the input as the only element, if not

                    function baggageHeaderToDynamicSamplingContext

                    baggageHeaderToDynamicSamplingContext: (
                    baggageHeader: string | string[] | number | null | undefined | boolean
                    ) => Partial<DynamicSamplingContext> | undefined;
                    • Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values from it.

                      Parameter baggageHeader

                      A very bread definition of a baggage header as it might appear in various frameworks.

                      Returns

                      The Dynamic Sampling Context that was found on baggageHeader, if there was any, undefined otherwise.

                    function basename

                    basename: (path: string, ext?: string) => string;
                    • JSDoc

                    function checkOrSetAlreadyCaught

                    checkOrSetAlreadyCaught: (exception: unknown) => boolean;
                    • Checks whether or not we've already captured the given exception (note: not an identical exception - the very object in question), and marks it captured if not.

                      This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This function helps us ensure that even if we encounter the same error more than once, we only record it the first time we see it.

                      Note: It will ignore primitives (always return false and not mark them as seen), as properties can't be set on them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent object wrapper forms so that this check will always work. However, because we need to flag the exact object which will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification must be done before the exception captured.

                      Parameter A

                      thrown exception to check or flag as having been seen

                      Returns

                      true if the exception has already been captured, false if not (with the side effect of marking it seen)

                    function consoleSandbox

                    consoleSandbox: <T>(callback: () => T) => T;
                    • Temporarily disable sentry console instrumentations.

                      Parameter callback

                      The function to run against the original console messages

                      Returns

                      The results of the callback

                    function convertToPlainObject

                    convertToPlainObject: <V>(
                    value: V
                    ) =>
                    | V
                    | {
                    [ownProps: string]: unknown;
                    type: string;
                    target: string;
                    currentTarget: string;
                    detail?: unknown;
                    }
                    | { [ownProps: string]: unknown; message: string; name: string; stack?: string };
                    • Transforms any Error or Event into a plain object with all of their enumerable properties, and some of their non-enumerable properties attached.

                      Parameter value

                      Initial source that we have to transform in order for it to be usable by the serializer

                      Returns

                      An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor an Error.

                    function createAttachmentEnvelopeItem

                    createAttachmentEnvelopeItem: (
                    attachment: Attachment,
                    textEncoder?: TextEncoderInternal
                    ) => AttachmentItem;
                    • Creates attachment envelope items

                    function createClientReportEnvelope

                    createClientReportEnvelope: (
                    discarded_events: ClientReport,
                    dsn?: string,
                    timestamp?: number
                    ) => ClientReportEnvelope;
                    • Creates client report envelope

                      Parameter discarded_events

                      An array of discard events

                      Parameter dsn

                      A DSN that can be set on the header. Optional.

                    function createEnvelope

                    createEnvelope: <E extends Envelope>(headers: E[0], items?: E[1]) => E;
                    • Creates an envelope. Make sure to always explicitly provide the generic to this function so that the envelope types resolve correctly.

                    function createEventEnvelopeHeaders

                    createEventEnvelopeHeaders: (
                    event: Event,
                    sdkInfo: SdkInfo | undefined,
                    tunnel: string | undefined,
                    dsn: DsnComponents
                    ) => EventEnvelopeHeaders;
                    • Creates event envelope headers, based on event, sdk info and tunnel Note: This function was extracted from the core package to make it available in Replay

                    function createStackParser

                    createStackParser: (...parsers: StackLineParser[]) => StackParser;
                    • Creates a stack parser with the supplied line parsers

                      StackFrames are returned in the correct order for Sentry Exception frames and with Sentry SDK internal frames removed from the top and bottom

                    function dateTimestampInSeconds

                    dateTimestampInSeconds: () => number;
                    • Returns a timestamp in seconds since the UNIX epoch using the Date API.

                    function dirname

                    dirname: (path: string) => string;
                    • JSDoc

                    function disabledUntil

                    disabledUntil: (limits: RateLimits, category: string) => number;
                    • Gets the time that the given category is disabled until for rate limiting. In case no category-specific limit is set but a general rate limit across all categories is active, that time is returned.

                      the time in ms that the category is disabled until or 0 if there's no active rate limit.

                    function dropUndefinedKeys

                    dropUndefinedKeys: <T>(inputValue: T) => T;
                    • Given any object, return a new object having removed all fields whose value was undefined. Works recursively on objects and arrays.

                      Attention: This function keeps circular references in the returned object.

                    function dsnFromString

                    dsnFromString: (str: string) => DsnComponents | undefined;
                    • Parses a Dsn from a given string.

                      Parameter str

                      A Dsn as string

                      Parameter str

                      is not a valid DSN string

                      Returns

                      Dsn as DsnComponents or undefined if

                    function dsnToString

                    dsnToString: (dsn: DsnComponents, withPassword?: boolean) => string;
                    • Renders the string representation of this Dsn.

                      By default, this will render the public representation without the password component. To get the deprecated private representation, set withPassword to true.

                      Parameter withPassword

                      When set to true, the password will be included.

                    function dynamicRequire

                    dynamicRequire: (mod: any, request: string) => any;
                    • Requires a module which is protected against bundler minification.

                      Parameter request

                      The module path to resolve

                    function dynamicSamplingContextToSentryBaggageHeader

                    dynamicSamplingContextToSentryBaggageHeader: (
                    dynamicSamplingContext?: DynamicSamplingContext
                    ) => string | undefined;
                    • Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-".

                      Parameter dynamicSamplingContext

                      The Dynamic Sampling Context to turn into a header. For convenience and compatibility with the getDynamicSamplingContext method on the Transaction class ,this argument can also be undefined. If it is undefined the function will return undefined.

                      Returns

                      a baggage header, created from dynamicSamplingContext, or undefined either if dynamicSamplingContext was undefined, or if dynamicSamplingContext didn't contain any values.

                    function envelopeContainsItemType

                    envelopeContainsItemType: (
                    envelope: Envelope,
                    types: EnvelopeItemType[]
                    ) => boolean;
                    • Returns true if the envelope contains any of the given envelope item types

                    function envelopeItemTypeToDataCategory

                    envelopeItemTypeToDataCategory: (type: EnvelopeItemType) => DataCategory;
                    • Maps the type of an envelope item to a data category.

                    function escapeStringForRegex

                    escapeStringForRegex: (regexString: string) => string;
                    • Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to new RegExp().

                      Parameter regexString

                      The string to escape

                      Returns

                      An version of the string with all special regex characters escaped

                    function eventFromMessage

                    eventFromMessage: (
                    stackParser: StackParser,
                    message: string,
                    level?: Severity | SeverityLevel,
                    hint?: EventHint,
                    attachStacktrace?: boolean
                    ) => Event;
                    • Builds and Event from a Message

                    function eventFromUnknownInput

                    eventFromUnknownInput: (
                    getCurrentHub: () => Hub,
                    stackParser: StackParser,
                    exception: unknown,
                    hint?: EventHint
                    ) => Event;
                    • Builds and Event from a Exception

                    function exceptionFromError

                    exceptionFromError: (stackParser: StackParser, error: Error) => Exception;
                    • Extracts stack frames from the error and builds a Sentry Exception

                    function extractExceptionKeysForMessage

                    extractExceptionKeysForMessage: (
                    exception: Record<string, unknown>,
                    maxLength?: number
                    ) => string;
                    • Given any captured exception, extract its keys and create a sorted and truncated list that will be used inside the event message. eg. Non-error exception captured with keys: foo, bar, baz

                    function extractPathForTransaction

                    extractPathForTransaction: (
                    req: PolymorphicRequest,
                    options?: { path?: boolean; method?: boolean; customRoute?: string }
                    ) => [string, TransactionSource];
                    • Extracts a complete and parameterized path from the request object and uses it to construct transaction name. If the parameterized transaction name cannot be extracted, we fall back to the raw URL.

                      Additionally, this function determines and returns the transaction name source

                      eg. GET /mountpoint/user/:id

                      Parameter req

                      A request object

                      Parameter options

                      What to include in the transaction name (method, path, or a custom route name to be used instead of the request's route)

                      Returns

                      A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url')

                    function extractRequestData

                    extractRequestData: (
                    req: PolymorphicRequest,
                    options?: { include?: string[]; deps?: InjectedNodeDeps }
                    ) => ExtractedNodeRequestData;
                    • Normalize data from the request object, accounting for framework differences.

                      Parameter req

                      The request object from which to extract data

                      Parameter

                      options.include An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_INCLUDES if not provided.

                      Parameter

                      options.deps Injected, platform-specific dependencies

                      Returns

                      An object containing normalized request data

                    function extractTraceparentData

                    extractTraceparentData: (traceparent?: string) => TraceparentData | undefined;
                    • Extract transaction context data from a sentry-trace header.

                      Parameter traceparent

                      Traceparent string

                      Returns

                      Object containing data from the header, or undefined if traceparent string is malformed

                    function fill

                    fill: (
                    source: { [key: string]: any },
                    name: string,
                    replacementFactory: (...args: any[]) => any
                    ) => void;
                    • Replace a method in an object with a wrapped version of itself.

                      Parameter source

                      An object that contains a method to be wrapped.

                      Parameter name

                      The name of the method to be wrapped.

                      Parameter replacementFactory

                      A higher-order function that takes the original version of the given method and returns a wrapped version. Note: The function returned by replacementFactory needs to be a non-arrow function, in order to preserve the correct value of this, and the original method must be called using `origMethod.call(this, <other args>) or origMethod.apply(this, [<other args>]) (rather than being called directly), again to preserve this`.

                      Returns

                      void

                    function forEachEnvelopeItem

                    forEachEnvelopeItem: <E extends Envelope>(
                    envelope: Envelope,
                    callback: (
                    envelopeItem: E[1][number],
                    envelopeItemType: E[1][number][0]['type']
                    ) => boolean | void
                    ) => boolean;
                    • Convenience function to loop through the items and item types of an envelope. (This function was mostly created because working with envelope types is painful at the moment)

                      If the callback returns true, the rest of the items will be skipped.

                    function generateSentryTraceHeader

                    generateSentryTraceHeader: (
                    traceId?: string,
                    spanId?: string,
                    sampled?: boolean
                    ) => string;
                    • Create sentry-trace header from span context values.

                    function getDomElement

                    getDomElement: <E = any>(selector: string) => E | null;
                    • Gets a DOM element by using document.querySelector.

                      This wrapper will first check for the existance of the function before actually calling it so that we don't have to take care of this check, every time we want to access the DOM.

                      Reason: DOM/querySelector is not available in all environments.

                      We have to cast to any because utils can be consumed by a variety of environments, and we don't want to break TS users. If you know what element will be selected by document.querySelector, specify it as part of the generic call. For example, const element = getDomElement<Element>('selector');

                      Parameter selector

                      the selector string passed on to document.querySelector

                    function getEventDescription

                    getEventDescription: (event: Event) => string;
                    • Extracts either message or type+value from an event that can be used for user-facing logs

                      Returns

                      event's description

                    function getFunctionName

                    getFunctionName: (fn: unknown) => string;
                    • Safely extract function name from itself

                    function getGlobalObject

                    getGlobalObject: <T>() => T & InternalGlobal;
                    • Deprecated

                      Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8

                    function getGlobalSingleton

                    getGlobalSingleton: <T>(
                    name: keyof InternalGlobal['__SENTRY__'],
                    creator: () => T,
                    obj?: unknown
                    ) => T;
                    • Returns a global singleton contained in the global __SENTRY__ object.

                      If the singleton doesn't already exist in __SENTRY__, it will be created using the given factory function and added to the __SENTRY__ object.

                      Parameter name

                      name of the global singleton on __SENTRY__

                      Parameter creator

                      creator Factory function to create the singleton if it doesn't already exist on __SENTRY__

                      Parameter obj

                      (Optional) The global object on which to look for __SENTRY__, if not GLOBAL_OBJ's return value

                      Returns

                      the singleton

                    function getLocationHref

                    getLocationHref: () => string;
                    • A safe form of location.href

                    function getNumberOfUrlSegments

                    getNumberOfUrlSegments: (url: string) => number;
                    • Returns number of URL segments of a passed string URL.

                    function getOriginalFunction

                    getOriginalFunction: (func: WrappedFunction) => WrappedFunction | undefined;
                    • This extracts the original function if available. See markFunctionWrapped for more information.

                      Parameter func

                      the function to unwrap

                      Returns

                      the unwrapped version of the function if available.

                    function getSanitizedUrlString

                    getSanitizedUrlString: (url: PartialURL) => string;
                    • Takes a URL object and returns a sanitized string which is safe to use as span description see: https://develop.sentry.dev/sdk/data-handling/#structuring-data

                    function getSdkMetadataForEnvelopeHeader

                    getSdkMetadataForEnvelopeHeader: (
                    metadataOrEvent?: SdkMetadata | Event
                    ) => SdkInfo | undefined;
                    • Extracts the minimal SDK info from from the metadata or an events

                    function getSDKSource

                    getSDKSource: () => SdkSource;
                    • Get source of SDK.

                    function htmlTreeAsString

                    htmlTreeAsString: (
                    elem: unknown,
                    options?: string[] | { keyAttrs?: string[]; maxStringLength?: number }
                    ) => string;
                    • Given a child DOM element, returns a query-selector statement describing that and its ancestors e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]

                      Returns

                      generated DOM path

                    function instrumentDOM

                    instrumentDOM: () => void;
                    • JSDoc

                    function instrumentXHR

                    instrumentXHR: () => void;
                    • JSDoc

                    function isAbsolute

                    isAbsolute: (path: string) => boolean;
                    • JSDoc

                    function isBrowserBundle

                    isBrowserBundle: () => boolean;
                    • Figures out if we're building a browser bundle.

                      Returns

                      true if this is a browser bundle build.

                    function isDOMError

                    isDOMError: (wat: unknown) => boolean;
                    • Checks whether given value's type is DOMError isDOMError.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isDOMException

                    isDOMException: (wat: unknown) => boolean;
                    • Checks whether given value's type is DOMException isDOMException.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isElement

                    isElement: (wat: unknown) => boolean;
                    • Checks whether given value's type is an Element instance isElement.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isError

                    isError: (wat: unknown) => wat is Error;
                    • Checks whether given value's type is one of a few Error or Error-like isError.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isErrorEvent

                    isErrorEvent: (wat: unknown) => boolean;
                    • Checks whether given value's type is ErrorEvent isErrorEvent.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isEvent

                    isEvent: (wat: unknown) => wat is PolymorphicEvent;
                    • Checks whether given value's type is an Event instance isEvent.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isInstanceOf

                    isInstanceOf: (wat: any, base: any) => boolean;
                    • Checks whether given value's type is an instance of provided constructor. isInstanceOf.

                      Parameter wat

                      A value to be checked.

                      Parameter base

                      A constructor to be used in a check.

                      Returns

                      A boolean representing the result.

                    function isMatchingPattern

                    isMatchingPattern: (
                    value: string,
                    pattern: RegExp | string,
                    requireExactStringMatch?: boolean
                    ) => boolean;
                    • Checks if the given value matches a regex or string

                      Parameter value

                      The string to test

                      Parameter pattern

                      Either a regex or a string against which value will be matched

                      Parameter requireExactStringMatch

                      If true, value must match pattern exactly. If false, value will match pattern if it contains pattern. Only applies to string-type patterns.

                    function isNaN

                    isNaN: (wat: unknown) => boolean;
                    • Checks whether given value is NaN isNaN.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isNativeFetch

                    isNativeFetch: (func: Function) => boolean;
                    • isNativeFetch checks if the given function is a native implementation of fetch()

                    function isNodeEnv

                    isNodeEnv: () => boolean;
                    • Checks whether we're in the Node.js or Browser environment

                      Returns

                      Answer to given question

                    function isPlainObject

                    isPlainObject: (wat: unknown) => wat is Record<string, unknown>;
                    • Checks whether given value's type is an object literal isPlainObject.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isPrimitive

                    isPrimitive: (wat: unknown) => wat is Primitive;
                    • Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) isPrimitive.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isRateLimited

                    isRateLimited: (limits: RateLimits, category: string, now?: number) => boolean;
                    • Checks if a category is rate limited

                    function isRegExp

                    isRegExp: (wat: unknown) => wat is RegExp;
                    • Checks whether given value's type is an regexp isRegExp.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isString

                    isString: (wat: unknown) => wat is string;
                    • Checks whether given value's type is a string isString.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isSyntheticEvent

                    isSyntheticEvent: (wat: unknown) => boolean;
                    • Checks whether given value's type is a SyntheticEvent isSyntheticEvent.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function isThenable

                    isThenable: (wat: any) => wat is PromiseLike<any>;
                    • Checks whether given value has a then function.

                      Parameter wat

                      A value to be checked.

                    function isVueViewModel

                    isVueViewModel: (wat: unknown) => boolean;
                    • Checks whether given value's type is a Vue ViewModel.

                      Parameter wat

                      A value to be checked.

                      Returns

                      A boolean representing the result.

                    function join

                    join: (...args: string[]) => string;
                    • JSDoc

                    function loadModule

                    loadModule: <T>(moduleName: string) => T | undefined;
                    • Helper for dynamically loading module that should work with linked dependencies. The problem is that we _should_ be using require(require.resolve(moduleName, { paths: [cwd()] })) However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during build time. require.resolve is also not available in any other way, so we cannot create, a fake helper like we do with dynamicRequire.

                      We always prefer to use local package, thus the value is not returned early from each try/catch block. That is to mimic the behavior of require.resolve exactly.

                      Parameter moduleName

                      module name to require

                      Returns

                      possibly required module

                    function makeDsn

                    makeDsn: (from: DsnLike) => DsnComponents | undefined;
                    • Creates a valid Sentry Dsn object, identifying a Sentry instance and project.

                      Parameter from

                      is an invalid DSN source

                      Returns

                      a valid DsnComponents object or undefined if

                    function makeFifoCache

                    makeFifoCache: <Key extends string, Value>(
                    size: number
                    ) => {
                    get: (key: Key) => Value | undefined;
                    add: (key: Key, value: Value) => void;
                    delete: (key: Key) => boolean;
                    clear: () => void;
                    size: () => number;
                    };
                    • Creates a cache that evicts keys in fifo order

                      Parameter size

                    function makePromiseBuffer

                    makePromiseBuffer: <T>(limit?: number) => PromiseBuffer<T>;
                    • Creates an new PromiseBuffer object with the specified limit

                      Parameter limit

                      max number of promises that can be stored in the buffer

                    function markFunctionWrapped

                    markFunctionWrapped: (
                    wrapped: WrappedFunction,
                    original: WrappedFunction
                    ) => void;
                    • Remembers the original function on the wrapped function and patches up the prototype.

                      Parameter wrapped

                      the wrapper function

                      Parameter original

                      the original function that gets wrapped

                    function memoBuilder

                    memoBuilder: () => MemoFunc;
                    • Helper to decycle json objects

                    function nodeStackLineParser

                    nodeStackLineParser: (getModule?: GetModuleFn) => StackLineParser;
                    • Node.js stack line parser

                      This is in @sentry/utils so it can be used from the Electron SDK in the browser for when nodeIntegration == true. This allows it to be used without referencing or importing any node specific code which causes bundlers to complain

                    function normalize

                    normalize: (input: unknown, depth?: number, maxProperties?: number) => any;
                    • Recursively normalizes the given object.

                      - Creates a copy to prevent original input mutation - Skips non-enumerable properties - When stringifying, calls toJSON if implemented - Removes circular references - Translates non-serializable values (undefined/NaN/functions) to serializable format - Translates known global objects/classes to a string representations - Takes care of Error object serialization - Optionally limits depth of final output - Optionally limits number of properties/elements included in any single object/array

                      Parameter input

                      The object to be normalized.

                      Parameter depth

                      The max depth to which to normalize the object. (Anything deeper stringified whole.)

                      Parameter maxProperties

                      The max number of elements or properties to be included in any single array or object in the normallized output.

                      Returns

                      A normalized version of the object, or "**non-serializable**" if any errors are thrown during normalization.

                    function normalizePath

                    normalizePath: (path: string) => string;
                    • JSDoc

                    function normalizeToSize

                    normalizeToSize: <T>(
                    object: { [key: string]: any },
                    depth?: number,
                    maxSize?: number
                    ) => T;
                    • JSDoc

                    function objectify

                    objectify: (wat: unknown) => typeof Object;
                    • Ensure that something is an object.

                      Turns undefined and null into Strings and all other primitives into instances of their respective wrapper classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.

                      Parameter wat

                      The subject of the objectification

                      Returns

                      A version of wat which can safely be used with Object class methods

                    function parseEnvelope

                    parseEnvelope: (
                    env: string | Uint8Array,
                    textEncoder: TextEncoderInternal,
                    textDecoder: TextDecoderInternal
                    ) => Envelope;
                    • Parses an envelope

                    function parseFetchArgs

                    parseFetchArgs: (fetchArgs: unknown[]) => { method: string; url: string };
                    • Parses the fetch arguments to find the used Http method and the url of the request

                    function parseRetryAfterHeader

                    parseRetryAfterHeader: (header: string, now?: number) => number;
                    • Extracts Retry-After value from the request header or returns default value

                      Parameter header

                      string representation of 'Retry-After' header

                      Parameter now

                      current unix timestamp

                    function parseSemver

                    parseSemver: (input: string) => SemVer;
                    • Parses input into a SemVer interface

                      Parameter input

                      string representation of a semver version

                    function parseStackFrames

                    parseStackFrames: (stackParser: StackParser, error: Error) => StackFrame[];
                    • Extracts stack frames from the error.stack string

                    function parseUrl

                    parseUrl: (url: string) => PartialURL;
                    • Parses string form of URL into an object // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B // intentionally using regex and not href parsing trick because React Native and other // environments where DOM might not be available

                      Returns

                      parsed URL object

                    function rejectedSyncPromise

                    rejectedSyncPromise: <T = never>(reason?: any) => PromiseLike<T>;
                    • Creates a rejected sync promise.

                      Parameter value

                      the value to reject the promise with

                      Returns

                      the rejected sync promise

                    function relative

                    relative: (from: string, to: string) => string;
                    • JSDoc

                    function resetInstrumentationHandlers

                    resetInstrumentationHandlers: () => void;
                    • Reset all instrumentation handlers. This can be used by tests to ensure we have a clean slate of instrumentation handlers.

                    function resolve

                    resolve: (...args: string[]) => string;
                    • JSDoc

                    function resolvedSyncPromise

                    resolvedSyncPromise: {
                    (): PromiseLike<void>;
                    <T>(value: T | PromiseLike<T>): PromiseLike<T>;
                    };

                      function safeJoin

                      safeJoin: (input: any[], delimiter?: string) => string;
                      • Join values in array

                        Parameter input

                        array of values to be joined together

                        Parameter delimiter

                        string to be placed in-between values

                        Returns

                        Joined values

                      function serializeEnvelope

                      serializeEnvelope: (
                      envelope: Envelope,
                      textEncoder?: TextEncoderInternal
                      ) => string | Uint8Array;
                      • Serializes an envelope.

                      function severityFromString

                      severityFromString: (level: Severity | SeverityLevel | string) => Severity;
                      • Converts a string-based level into a member of the deprecated Severity enum.

                        Parameter level

                        String representation of Severity

                        Returns

                        Severity

                        Deprecated

                        severityFromString is deprecated. Please use severityLevelFromString instead.

                      function severityLevelFromString

                      severityLevelFromString: (level: SeverityLevel | string) => SeverityLevel;
                      • Converts a string-based level into a SeverityLevel, normalizing it along the way.

                        Parameter level

                        String representation of desired SeverityLevel.

                        Returns

                        The SeverityLevel corresponding to the given string, or 'log' if the string isn't a valid level.

                      function snipLine

                      snipLine: (line: string, colno: number) => string;
                      • This is basically just trim_line from https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67

                        Parameter str

                        An object that contains serializable values

                        Parameter max

                        Maximum number of characters in truncated string

                        Returns

                        string Encoded

                      function stackParserFromStackParserOptions

                      stackParserFromStackParserOptions: (
                      stackParser: StackParser | StackLineParser[]
                      ) => StackParser;
                      • Gets a stack parser implementation from Options.stackParser

                        See Also

                        • Options

                          If options contains an array of line parsers, it is converted into a parser

                      function stringMatchesSomePattern

                      stringMatchesSomePattern: (
                      testString: string,
                      patterns?: Array<string | RegExp>,
                      requireExactStringMatch?: boolean
                      ) => boolean;
                      • Test the given string against an array of strings and regexes. By default, string matching is done on a substring-inclusion basis rather than a strict equality basis

                        Parameter testString

                        The string to test

                        Parameter patterns

                        The patterns against which to test the string

                        Parameter requireExactStringMatch

                        If true, testString must match one of the given string patterns exactly in order to count. If false, testString will match a string pattern if it contains that pattern.

                        Returns

                      function stripSentryFramesAndReverse

                      stripSentryFramesAndReverse: (stack: ReadonlyArray<StackFrame>) => StackFrame[];
                      • Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames. Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the function that caused the crash is the last frame in the array.

                      function stripUrlQueryAndFragment

                      stripUrlQueryAndFragment: (urlPath: string) => string;
                      • Strip the query string and fragment off of a given URL or path (if present)

                        Parameter urlPath

                        Full URL or path, including possible query string and/or fragment

                        Returns

                        URL or path without query string or fragment

                      function supportsDOMError

                      supportsDOMError: () => boolean;
                      • Tells whether current environment supports DOMError objects supportsDOMError.

                        Returns

                        Answer to the given question.

                      function supportsDOMException

                      supportsDOMException: () => boolean;
                      • Tells whether current environment supports DOMException objects supportsDOMException.

                        Returns

                        Answer to the given question.

                      function supportsErrorEvent

                      supportsErrorEvent: () => boolean;
                      • Tells whether current environment supports ErrorEvent objects supportsErrorEvent.

                        Returns

                        Answer to the given question.

                      function supportsFetch

                      supportsFetch: () => boolean;
                      • Tells whether current environment supports Fetch API supportsFetch.

                        Returns

                        Answer to the given question.

                      function supportsHistory

                      supportsHistory: () => boolean;
                      • Tells whether current environment supports History API supportsHistory.

                        Returns

                        Answer to the given question.

                      function supportsNativeFetch

                      supportsNativeFetch: () => boolean;
                      • Tells whether current environment supports Fetch API natively supportsNativeFetch.

                        Returns

                        true if window.fetch is natively implemented, false otherwise

                      function supportsReferrerPolicy

                      supportsReferrerPolicy: () => boolean;
                      • Tells whether current environment supports Referrer Policy API supportsReferrerPolicy.

                        Returns

                        Answer to the given question.

                      function supportsReportingObserver

                      supportsReportingObserver: () => boolean;
                      • Tells whether current environment supports ReportingObserver API supportsReportingObserver.

                        Returns

                        Answer to the given question.

                      function timestampInSeconds

                      timestampInSeconds: () => number;
                      • Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the availability of the Performance API.

                        See usingPerformanceAPI to test whether the Performance API is used.

                        BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is asleep. This creates a skew between dateTimestampInSeconds and timestampInSeconds. The skew can grow to arbitrary amounts like days, weeks or months. See https://github.com/getsentry/sentry-javascript/issues/2590.

                      function timestampWithMs

                      timestampWithMs: () => number;
                      • Re-exported with an old name for backwards-compatibility. TODO (v8): Remove this

                        Deprecated

                        Use timestampInSeconds instead.

                      function tracingContextFromHeaders

                      tracingContextFromHeaders: (
                      sentryTrace: Parameters<typeof extractTraceparentData>[0],
                      baggage: Parameters<typeof baggageHeaderToDynamicSamplingContext>[0]
                      ) => {
                      traceparentData: ReturnType<typeof extractTraceparentData>;
                      dynamicSamplingContext: ReturnType<typeof baggageHeaderToDynamicSamplingContext>;
                      propagationContext: PropagationContext;
                      };
                      • Create tracing context from incoming headers.

                      function truncate

                      truncate: (str: string, max?: number) => string;
                      • Truncates given string to the maximum characters count

                        Parameter str

                        An object that contains serializable values

                        Parameter max

                        Maximum number of characters in truncated string (0 = unlimited)

                        Returns

                        string Encoded

                      function updateRateLimits

                      updateRateLimits: (
                      limits: RateLimits,
                      { statusCode, headers }: TransportMakeRequestResponse,
                      now?: number
                      ) => RateLimits;
                      • Update ratelimits from incoming headers.

                        the updated RateLimits object.

                      function urlEncode

                      urlEncode: (object: { [key: string]: any }) => string;
                      • Encodes given object into url-friendly format

                        Parameter object

                        An object that contains serializable values

                        Returns

                        string Encoded

                      function uuid4

                      uuid4: () => string;
                      • UUID4 generator

                        Returns

                        string Generated UUID4.

                      function walk

                      walk: (
                      key: string,
                      value: unknown,
                      depth?: number,
                      maxProperties?: number,
                      memo?: MemoFunc
                      ) => Primitive | ObjOrArray<unknown>;
                      • Visits a node to perform normalization on it

                        Parameter key

                        The key corresponding to the given node

                        Parameter value

                        The node to be visited

                        Parameter depth

                        Optional number indicating the maximum recursion depth

                        Parameter maxProperties

                        Optional maximum number of properties/elements included in any single object/array

                        Parameter memo

                        Optional Memo class handling decycling

                      Classes

                      class SentryError

                      class SentryError extends Error {}
                      • An error emitted by Sentry SDKs and related utilities.

                      constructor

                      constructor(
                      message: string,
                      logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'log' | 'assert' | 'trace'
                      );

                        property logLevel

                        logLevel: 'debug' | 'info' | 'warn' | 'error' | 'log' | 'assert' | 'trace';

                          property message

                          message: string;

                            property name

                            name: string;
                            • Display name of this error instance.

                            class SyncPromise

                            class SyncPromise<T> implements PromiseLike<T> {}
                            • Thenable class that behaves like a Promise and follows it's interface but is not async internally

                            constructor

                            constructor(
                            executor: (
                            resolve: (value?: T | PromiseLike<T> | null) => void,
                            reject: (reason?: any) => void
                            ) => void
                            );

                              method catch

                              catch: <TResult = never>(
                              onrejected?: (reason: any) => TResult | PromiseLike<TResult>
                              ) => PromiseLike<T | TResult>;
                              • JSDoc

                              method finally

                              finally: <TResult>(onfinally?: (() => void) | null) => PromiseLike<TResult>;
                              • JSDoc

                              method then

                              then: <TResult1 = T, TResult2 = never>(
                              onfulfilled?: (value: T) => TResult1 | PromiseLike<TResult1>,
                              onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>
                              ) => PromiseLike<TResult1 | TResult2>;
                              • JSDoc

                              Interfaces

                              interface AddRequestDataToEventOptions

                              interface AddRequestDataToEventOptions {}
                              • Options deciding what parts of the request to use when enhancing an event

                              property deps

                              deps?: {
                              cookie: {
                              parse: (cookieStr: string) => Record<string, string>;
                              };
                              url: {
                              parse: (urlStr: string) => {
                              query: string | null;
                              };
                              };
                              };
                              • Injected platform-specific dependencies

                              property include

                              include?: {
                              ip?: boolean;
                              request?: boolean | string[];
                              transaction?: boolean | TransactionNamingScheme;
                              user?: boolean | string[];
                              };
                              • Flags controlling whether each type of data should be added to the event

                              interface InternalGlobal

                              interface InternalGlobal {}
                              • Internal global with common properties and Sentry extensions

                              property console

                              console: Console;

                                property navigator

                                navigator?: {
                                userAgent?: string;
                                };

                                  property onerror

                                  onerror?: {
                                  (
                                  msg: unknown,
                                  url: unknown,
                                  line: unknown,
                                  column: unknown,
                                  error: unknown
                                  ): boolean;
                                  __SENTRY_INSTRUMENTED__?: true;
                                  __SENTRY_LOADER__?: true;
                                  };

                                    property onunhandledrejection

                                    onunhandledrejection?: {
                                    (event: unknown): boolean;
                                    __SENTRY_INSTRUMENTED__?: true;
                                    __SENTRY_LOADER__?: true;
                                    };

                                      property Sentry

                                      Sentry?: {
                                      Integrations?: Integration[];
                                      };

                                        property SENTRY_DSN

                                        SENTRY_DSN?: string;

                                          property SENTRY_ENVIRONMENT

                                          SENTRY_ENVIRONMENT?: string;

                                            property SENTRY_RELEASE

                                            SENTRY_RELEASE?: {
                                            id?: string;
                                            };

                                              property SENTRY_SDK_SOURCE

                                              SENTRY_SDK_SOURCE?: SdkSource;

                                                interface PromiseBuffer

                                                interface PromiseBuffer<T> {}

                                                  property $

                                                  $: Array<PromiseLike<T>>;

                                                    method add

                                                    add: (taskProducer: () => PromiseLike<T>) => PromiseLike<T>;

                                                      method drain

                                                      drain: (timeout?: number) => PromiseLike<boolean>;

                                                        interface TextDecoderInternal

                                                        interface TextDecoderInternal {}

                                                          method decode

                                                          decode: (input?: Uint8Array) => string;

                                                            Type Aliases

                                                            type ConsoleLevel

                                                            type ConsoleLevel = (typeof CONSOLE_LEVELS)[number];

                                                              type InstrumentHandlerCallback

                                                              type InstrumentHandlerCallback = (data: any) => void;

                                                                type InstrumentHandlerType

                                                                type InstrumentHandlerType =
                                                                | 'console'
                                                                | 'dom'
                                                                | 'fetch'
                                                                | 'history'
                                                                | 'sentry'
                                                                | 'xhr'
                                                                | 'error'
                                                                | 'unhandledrejection';

                                                                  type IntegrationWithExclusionOption

                                                                  type IntegrationWithExclusionOption = Integration & {
                                                                  /**
                                                                  * Allow the user to exclude this integration by not returning it from a function provided as the `integrations` option
                                                                  * in `Sentry.init()`. Meant to be used with default integrations, the idea being that if a user has actively filtered
                                                                  * an integration out, we should be able to respect that choice if we wish.
                                                                  */
                                                                  allowExclusionByUser?: boolean;
                                                                  };

                                                                    type MemoFunc

                                                                    type MemoFunc = [(obj: any) => boolean, (obj: any) => void];

                                                                      type RateLimits

                                                                      type RateLimits = Record<string, number>;

                                                                        type SdkSource

                                                                        type SdkSource = 'npm' | 'cdn' | 'loader';

                                                                          type UserIntegrations

                                                                          type UserIntegrations = Integration[] | UserIntegrationsFunction;

                                                                            type UserIntegrationsFunction

                                                                            type UserIntegrationsFunction = (integrations: Integration[]) => Integration[];

                                                                              Package Files (35)

                                                                              Dependencies (2)

                                                                              Dev Dependencies (3)

                                                                              Peer Dependencies (0)

                                                                              No peer dependencies.

                                                                              Badge

                                                                              To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                              You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@sentry/utils.

                                                                              • Markdown
                                                                                [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@sentry/utils)
                                                                              • HTML
                                                                                <a href="https://www.jsdocs.io/package/@sentry/utils"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>