@sentry/utils

  • Version 6.5.1
  • Published
  • 554 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

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 logger

const logger: Logger;

    variable usingPerformanceAPI

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

    Functions

    function addContextToFrame

    addContextToFrame: (
    lines: string[],
    frame: any,
    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: any, mechanism?: { [key: string]: any }) => void;
    • Adds exception mechanism to a given event.

      Parameter event

      The event to modify.

      Parameter mechanism

      Mechanism of the mechanism.

    function addExceptionTypeValue

    addExceptionTypeValue: (event: any, 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: (handler: InstrumentHandler) => 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 basename

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

    function consoleSandbox

    consoleSandbox: (callback: () => any) => any;
    • JSDoc

    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 dropUndefinedKeys

    dropUndefinedKeys: <T>(val: T) => T;
    • Given any object, return the new object with removed keys that value was undefined. Works recursively on objects and arrays.

    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 extractExceptionKeysForMessage

    extractExceptionKeysForMessage: (exception: any, 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 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 forget

    forget: (promise: PromiseLike<any>) => void;
    • Consumes the promise and logs the error when it rejects.

      Parameter promise

      A promise to forget.

    function getEventDescription

    getEventDescription: (event: any) => 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 getLocationHref

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

    function htmlTreeAsString

    htmlTreeAsString: (elem: unknown) => 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 isDOMError

    isDOMError: (wat: any) => 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: any) => 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: any) => 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: any) => boolean;
    • 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: any) => 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: any) => boolean;
    • 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 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: any) => boolean;
    • 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: any) => wat is any;
    • Checks whether given value's 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 isRegExp

    isRegExp: (wat: any) => boolean;
    • 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: any) => boolean;
    • 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: any) => 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) => boolean;
    • 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 normalize

    normalize: (input: any, depth?: number) => any;
    • normalize()

      - Creates a copy to prevent original input mutation - Skip non-enumerablers - Calls toJSON if implemented - Removes circular references - Translates non-serializeable values (undefined/NaN/Functions) to serializable format - Translates known global objects/Classes to a string representations - Takes care of Error objects serialization - Optionally limit depth of final output

    function normalizePath

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

    function normalizeToSize

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

    function parseRetryAfterHeader

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

      Parameter now

      current unix timestamp

      Parameter header

      string representation of 'Retry-After' header

    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 relative

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

    function resolve

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

    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 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 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 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: any, depth?: number, memo?: Memo) => any;
      • Walks an object to perform a normalization on it

        Parameter key

        of object that's walked in current iteration

        Parameter value

        object to be walked

        Parameter depth

        Optional number indicating how deep should walking be performed

        Parameter memo

        Optional Memo class handling decycling

      Classes

      class Dsn

      class Dsn implements DsnComponents {}
      • The Sentry Dsn, identifying a Sentry instance and project.

      constructor

      constructor(from: any);
      • Creates a new Dsn component

      property host

      host: string;
      • Hostname of the Sentry instance.

      property pass

      pass: string;
      • Private authorization key (deprecated, optional).

      property path

      path: string;
      • Path

      property port

      port: string;
      • Port of the Sentry instance.

      property projectId

      projectId: string;
      • Project ID

      property protocol

      protocol: any;
      • Protocol used to connect to Sentry.

      property publicKey

      publicKey: string;
      • Public authorization key.

      property user

      user: string;
      • Public authorization key (deprecated, renamed to publicKey).

      method toString

      toString: (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.

      class Memo

      class Memo {}
      • Memo class used for decycle json objects. Uses WeakSet if available otherwise array.

      constructor

      constructor();

        method memoize

        memoize: (obj: any) => boolean;
        • Sets obj to remember.

          Parameter obj

          Object to remember

        method unmemoize

        unmemoize: (obj: any) => void;
        • Removes object from internal storage.

          Parameter obj

          Object to forget

        class PromiseBuffer

        class PromiseBuffer<T> {}
        • A simple queue that holds promises.

        constructor

        constructor(_limit?: number);

          method add

          add: (task: PromiseLike<T>) => PromiseLike<T>;
          • Add a promise to the queue.

            Parameter task

            Can be any PromiseLike

            Returns

            The original promise.

          method drain

          drain: (timeout?: number) => PromiseLike<boolean>;
          • This will drain the whole queue, returns true if queue is empty or drained. If timeout is provided and the queue takes longer to drain, the promise still resolves but with false.

            Parameter timeout

            Number in ms to wait until it resolves with false.

          method isReady

          isReady: () => boolean;
          • Says if the buffer is ready to take more requests

          method length

          length: () => number;
          • This function returns the number of unresolved promises in the queue.

          method remove

          remove: (task: PromiseLike<T>) => PromiseLike<T>;
          • Remove a promise to the queue.

            Parameter task

            Can be any PromiseLike

            Returns

            Removed promise.

          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 all

                static all: <U = any>(collection: Array<U | PromiseLike<U>>) => PromiseLike<U[]>;
                • JSDoc

                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 reject

                static reject: <T = never>(reason?: any) => PromiseLike<T>;
                • JSDoc

                method resolve

                static resolve: <T>(value: T | PromiseLike<T>) => PromiseLike<T>;
                • JSDoc

                method then

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

                method toString

                toString: () => string;
                • JSDoc

                Package Files (19)

                Dependencies (2)

                Dev Dependencies (7)

                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>