@sentry/utils

  • Version 7.4.1
  • Published
  • 736 kB
  • 2 dependencies
  • BSD-3-Clause 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 logger

        let 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 SENTRY_BAGGAGE_KEY_PREFIX

          const SENTRY_BAGGAGE_KEY_PREFIX: string;

            variable SENTRY_BAGGAGE_KEY_PREFIX_REGEX

            const SENTRY_BAGGAGE_KEY_PREFIX_REGEX: RegExp;

              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 addRequestDataToEvent

                  addRequestDataToEvent: (
                  event: Event,
                  req: CrossPlatformRequest,
                  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: CrossPlatformRequest,
                  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 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 extends unknown>(
                  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 createBaggage

                  createBaggage: (
                  initItems: BaggageObj,
                  baggageString?: string,
                  mutable?: boolean
                  ) => Baggage;
                  • Create an instance of Baggage

                  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 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 given category is disabled until for rate limiting

                  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 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 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().

                    Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node 12+).

                    Parameter regexString

                    The string to escape

                    Returns

                    An version of the string with all special regex characters escaped

                  function extensionRelayDSN

                  extensionRelayDSN: (originalDsn: string | undefined) => string | undefined;
                  • Changes a Dsn to point to the relay server running in the Lambda Extension.

                    This is only used by the serverless integration for AWS Lambda.

                    Parameter originalDsn

                    The original Dsn of the customer.

                    Returns

                    Dsn pointing to Lambda extension.

                  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: CrossPlatformRequest,
                  options?: { path?: boolean; method?: boolean }
                  ) => string;
                  • Extracts complete generalized path from the request object and uses it to construct transaction name.

                    eg. GET /mountpoint/user/:id

                    Parameter req

                    A request object

                    Parameter options

                    What to include in the transaction name (method, path, or both)

                    Returns

                    The fully constructed transaction name

                  function extractRequestData

                  extractRequestData: (
                  req: CrossPlatformRequest,
                  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']
                  ) => void
                  ) => void;
                  • 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)

                  function getBaggageValue

                  getBaggageValue: (
                  baggage: Baggage,
                  key: keyof BaggageObj
                  ) => BaggageObj[keyof BaggageObj];
                  • Get a value from baggage

                  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 & SentryGlobal;
                  • Safely get global scope object

                    Returns

                    Global scope object

                  function getGlobalSingleton

                  getGlobalSingleton: <T>(
                  name: keyof SentryGlobal['__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 getGlobalObject's return value

                    Returns

                    the singleton

                  function getLocationHref

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

                  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 getSentryBaggageItems

                  getSentryBaggageItems: (baggage: Baggage) => BaggageObj;
                  • Returns Sentry specific baggage values

                  function getThirdPartyBaggage

                  getThirdPartyBaggage: (baggage: Baggage) => string;
                  • Returns 3rd party baggage string of

                    Parameter baggage

                    Parameter baggage

                  function htmlTreeAsString

                  htmlTreeAsString: (elem: unknown, keyAttrs?: string[]) => 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 isAbsolute

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

                  function isBaggageMutable

                  isBaggageMutable: (baggage: Baggage) => boolean;
                  • Checks if baggage is mutable

                    Parameter baggage

                    Returns

                    true if baggage is mutable, else false

                  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) => boolean;
                  • Checks if the value matches a regex or includes the string

                    Parameter value

                    The string value to be checked against

                    Parameter pattern

                    Either a regex or a string that must be contained in value

                  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 isSentryBaggageEmpty

                  isSentryBaggageEmpty: (baggage: Baggage) => boolean;
                  • Check if the Sentry part of the passed baggage (i.e. the first element in the tuple) is empty

                  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 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;
                  • The Sentry Dsn, identifying a Sentry instance and project.

                  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 mergeAndSerializeBaggage

                  mergeAndSerializeBaggage: (
                  incomingBaggage?: Baggage,
                  thirdPartyBaggageHeader?: HttpHeaderValue
                  ) => string;
                  • Merges the baggage header we saved from the incoming request (or meta tag) with a possibly created or modified baggage header by a third party that's been added to the outgoing request header.

                    In case

                    Parameter headerBaggageString

                    exists, we can safely add the the 3rd party part of

                    Parameter headerBaggage

                    with our

                    Parameter

                    incomingBaggage. This is possible because if we modified anything beforehand, it would only affect parts of the sentry baggage (@see Baggage interface).

                    Parameter incomingBaggage

                    the baggage header of the incoming request that might contain sentry entries

                    Parameter thirdPartyBaggageHeader

                    possibly existing baggage header string or string[] added from a third party to the request headers

                    a merged and serialized baggage string to be propagated with the outgoing request

                  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 parseBaggageHeader

                  parseBaggageHeader: (
                  inputBaggageValue: HttpHeaderValue,
                  includeThirdPartyEntries?: boolean
                  ) => Baggage;
                  • Parse a baggage header from a string or a string array and return a Baggage object

                    If

                    Parameter includeThirdPartyEntries

                    is set to true, third party baggage entries are added to the Baggage object (This is necessary for merging potentially pre-existing baggage headers in outgoing requests with our sentry- values)

                  function parseBaggageSetMutability

                  parseBaggageSetMutability: (
                  rawBaggageValue: HttpHeaderValue | false | undefined,
                  sentryTraceHeader: TraceparentData | string | false | undefined | null
                  ) => Baggage;
                  • Helper function that takes a raw baggage string (if available) and the processed sentry-trace header data (if available), parses the baggage string and creates a Baggage object If there is no baggage string, it will create an empty Baggage object. In a second step, this functions determines if the created Baggage object should be set immutable to prevent mutation of the Sentry data.

                    Extracted this logic to a function because it's duplicated in a lot of places.

                    Parameter rawBaggageValue

                    Parameter sentryTraceHeader

                  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 parseUrl

                  parseUrl: (url: string) => {
                  host?: string;
                  path?: string;
                  protocol?: string;
                  relative?: string;
                  };
                  • 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 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 serializeBaggage

                    serializeBaggage: (baggage: Baggage) => string;
                    • Serialize a baggage object

                    function serializeEnvelope

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

                    function setBaggageImmutable

                    setBaggageImmutable: (baggage: Baggage) => void;
                    • Sets the passed baggage immutable

                      Parameter baggage

                    function setBaggageValue

                    setBaggageValue: (
                    baggage: Baggage,
                    key: keyof BaggageObj,
                    value: BaggageObj[keyof BaggageObj]
                    ) => void;
                    • Add a value to baggage

                    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 stripSentryFramesAndReverse

                    stripSentryFramesAndReverse: (stack: StackFrame[]) => StackFrame[];

                    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;

                      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. Returns true if headers contains a non-empty rate limiting header.

                      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);

                        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 PromiseBuffer

                            interface PromiseBuffer<T> {}

                              property $

                              $: Array<PromiseLike<T>>;

                                method add

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

                                  method drain

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

                                    Type Aliases

                                    type CrossPlatformRequest

                                    type CrossPlatformRequest = BaseRequest &
                                    BrowserRequest &
                                    NodeRequest &
                                    ExpressRequest &
                                    KoaRequest &
                                    NextjsRequest;
                                    • A Request type compatible with Node, Express, browser, etc., because everything is optional

                                    type InstrumentHandlerCallback

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

                                      type InstrumentHandlerType

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

                                        type MemoFunc

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

                                          type RateLimits

                                          type RateLimits = Record<string, number>;

                                            Package Files (28)

                                            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>