@firebase/util

  • Version 1.1.0
  • Published
  • 545 kB
  • 1 dependency
  • Apache-2.0 license

Install

npm i @firebase/util
yarn add @firebase/util
pnpm add @firebase/util

Overview

_NOTE: This is specifically tailored for Firebase JS SDK usage, if you are not a member of the Firebase team, please avoid using this package_

Index

Variables

variable base64

const base64: Base64;

    variable CONSTANTS

    const CONSTANTS: { NODE_CLIENT: boolean; NODE_ADMIN: boolean; SDK_VERSION: string };
    • Firebase constants. Some of these (@defines) can be overridden at compile-time.

    variable MAX_VALUE_MILLIS

    const MAX_VALUE_MILLIS: number;
    • The maximum milliseconds to increase to.

      Visible for testing

    variable RANDOM_FACTOR

    const RANDOM_FACTOR: number;
    • The percentage of backoff time to randomize by. See http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic for context.

      Visible for testing

    Functions

    function areCookiesEnabled

    areCookiesEnabled: () => boolean;
    • This method checks whether cookie is enabled within current browser true if cookie is enabled within current browser

    function assert

    assert: (assertion: unknown, message: string) => void;
    • Throws an error if the provided assertion is falsy

    function assertionError

    assertionError: (message: string) => Error;
    • Returns an Error object suitable for throwing.

    function async

    async: (fn: Function, onError?: ErrorFn) => Function;
    • Turn synchronous function into one called asynchronously.

    function base64Decode

    base64Decode: (str: string) => string | null;
    • URL-safe base64 decoding

      NOTE: DO NOT use the global atob() function - it does NOT support the base64Url variant encoding.

      Parameter str

      To be decoded Decoded result, if possible

    function base64Encode

    base64Encode: (str: string) => string;
    • URL-safe base64 encoding

    function calculateBackoffMillis

    calculateBackoffMillis: (
    backoffCount: number,
    intervalMillis?: number,
    backoffFactor?: number
    ) => number;
    • Based on the backoff method from https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.

    function contains

    contains: <T extends object>(obj: T, key: string) => boolean;
    • Copyright 2017 Google LLC

      Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

    function createMockUserToken

    createMockUserToken: (
    token: EmulatorMockTokenOptions,
    projectId?: string
    ) => string;

      function createSubscribe

      createSubscribe: <T>(
      executor: Executor<T>,
      onNoObservers?: Executor<T>
      ) => Subscribe<T>;
      • Helper to make a Subscribe function (just like Promise helps make a Thenable).

        Parameter executor

        Function which can make calls to a single Observer as a proxy.

        Parameter onNoObservers

        Callback when count of Observers goes to zero.

      function decode

      decode: (token: string) => DecodedToken;
      • Decodes a Firebase auth. token into constituent parts.

        Notes: - May return with invalid / incomplete claims if there's no native base64 decoding support. - Doesn't check if the token is actually valid.

      function deepCopy

      deepCopy: <T>(value: T) => T;
      • Do a deep-copy of basic JavaScript Objects or Arrays.

      function deepExtend

      deepExtend: (target: unknown, source: unknown) => unknown;
      • Copy properties from source to target (recursively allows extension of Objects and Arrays). Scalar values in the target are over-written. If target is undefined, an object of the appropriate type will be created (and returned).

        We recursively copy all child properties of plain Objects in the source- so that namespace- like dictionaries are merged.

        Note that the target can be a function, in which case the properties in the source Object are copied onto it as static properties of the Function.

        Note: we don't merge __proto__ to prevent prototype pollution

      function errorPrefix

      errorPrefix: (fnName: string, argName: string) => string;
      • Generates a string to prefix an error message about failed argument validation

        Parameter fnName

        The function name

        Parameter argName

        The name of the argument The prefix to add to the error thrown for validation.

      function extractQuerystring

      extractQuerystring: (url: string) => string;
      • Extract the query string part of a URL, including the leading question mark (if present).

      function getGlobal

      getGlobal: () => typeof globalThis;
      • Polyfill for globalThis object.

        Returns

        the globalThis object for the given environment.

      function getModularInstance

      getModularInstance: <ExpService>(
      service: Compat<ExpService> | ExpService
      ) => ExpService;

        function getUA

        getUA: () => string;
        • Returns navigator.userAgent string or '' if it's not defined. user agent string

        function isAdmin

        isAdmin: (token: string) => boolean;
        • Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.

          Notes: - May return a false negative if there's no native base64 decoding support. - Doesn't check if the token is actually valid.

        function isBrowser

        isBrowser: () => boolean;
        • Detect Browser Environment

        function isBrowserExtension

        isBrowserExtension: () => boolean;

          function isElectron

          isElectron: () => boolean;
          • Detects Electron apps.

          function isEmpty

          isEmpty: (obj: object) => obj is {};

            function isIE

            isIE: () => boolean;
            • Detects Internet Explorer.

            function isIndexedDBAvailable

            isIndexedDBAvailable: () => boolean;
            • This method checks if indexedDB is supported by current browser/service worker context true if indexedDB is supported by current browser/service worker context

            function isMobileCordova

            isMobileCordova: () => boolean;
            • Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.

              Deliberately does not rely on checking file:// URLs (as this fails PhoneGap in the Ripple emulator) nor Cordova onDeviceReady, which would normally wait for a callback.

            function isNode

            isNode: () => boolean;
            • Detect Node.js.

              true if Node.js environment is detected.

            function isNodeSdk

            isNodeSdk: () => boolean;
            • Detect whether the current SDK build is the Node version.

              true if it's the Node SDK build.

            function isReactNative

            isReactNative: () => boolean;
            • Detect React Native.

              true if ReactNative environment is detected.

            function isSafari

            isSafari: () => boolean;
            • Returns true if we are running in Safari.

            function issuedAtTime

            issuedAtTime: (token: string) => number | null;
            • Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.

              Notes: - May return null if there's no native base64 decoding support. - Doesn't check if the token is actually valid.

            function isUWP

            isUWP: () => boolean;
            • Detects Universal Windows Platform apps.

            function isValidFormat

            isValidFormat: (token: string) => boolean;
            • Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.

              Notes: - May return a false negative if there's no native base64 decoding support. - Doesn't check if the token is actually valid.

            function isValidTimestamp

            isValidTimestamp: (token: string) => boolean;
            • Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.

              Notes: - May return a false negative if there's no native base64 decoding support. - Doesn't check if the token is actually valid.

            function jsonEval

            jsonEval: (str: string) => unknown;
            • Evaluates a JSON string into a javascript object.

              Parameter str

              A string containing JSON. {*} The javascript object representing the specified JSON.

            function map

            map: <K extends string, V, U>(
            obj: { [key in K]: V },
            fn: (value: V, key: K, obj: { [key in K]: V }) => U,
            contextObj?: unknown
            ) => { [key in K]: U };

              function ordinal

              ordinal: (i: number) => string;
              • Provide English ordinal letters after a number

              function querystring

              querystring: (querystringParams: { [key: string]: string | number }) => string;
              • Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a params object (e.g. {arg: 'val', arg2: 'val2'}) Note: You must prepend it with ? when adding it to a URL.

              function querystringDecode

              querystringDecode: (querystring: string) => Record<string, string>;
              • Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object (e.g. {arg: 'val', arg2: 'val2'})

              function safeGet

              safeGet: <T extends object, K extends keyof T>(
              obj: T,
              key: K
              ) => T[K] | undefined;

                function stringify

                stringify: (data: unknown) => string;
                • Returns JSON representing a javascript object.

                  Parameter data

                  Javascript object to be stringified. {string} The JSON contents of the object.

                function stringLength

                stringLength: (str: string) => number;
                • Calculate length without actually converting; useful for doing cheaper validation.

                  Parameter str

                  {number}

                function stringToByteArray

                stringToByteArray: (str: string) => number[];
                • Parameter str

                  {Array}

                function validateArgCount

                validateArgCount: (
                fnName: string,
                minCount: number,
                maxCount: number,
                argCount: number
                ) => void;
                • Check to make sure the appropriate number of arguments are provided for a public function. Throws an error if it fails.

                  Parameter fnName

                  The function name

                  Parameter minCount

                  The minimum number of arguments to allow for the function call

                  Parameter maxCount

                  The maximum number of argument to allow for the function call

                  Parameter argCount

                  The actual number of arguments provided.

                function validateCallback

                validateCallback: (
                fnName: string,
                argumentName: string,
                callback: Function,
                optional: boolean
                ) => void;

                  function validateContextObject

                  validateContextObject: (
                  fnName: string,
                  argumentName: string,
                  context: unknown,
                  optional: boolean
                  ) => void;

                    function validateIndexedDBOpenable

                    validateIndexedDBOpenable: () => Promise<boolean>;
                    • This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject if errors occur during the database open operation.

                      Throws

                      exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox private browsing)

                    function validateNamespace

                    validateNamespace: (
                    fnName: string,
                    namespace: string,
                    optional: boolean
                    ) => void;
                    • Parameter fnName

                      Parameter argumentNumber

                      Parameter namespace

                      Parameter optional

                    Classes

                    class Deferred

                    class Deferred<R> {}
                    • Copyright 2017 Google LLC

                      Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

                      http://www.apache.org/licenses/LICENSE-2.0

                      Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

                    constructor

                    constructor();

                      property promise

                      promise: Promise<R>;

                        property reject

                        reject: (value?: unknown) => void;

                          property resolve

                          resolve: (value?: unknown) => void;

                            method wrapCallback

                            wrapCallback: (
                            callback?: (error?: unknown, value?: unknown) => void
                            ) => (error: unknown, value?: unknown) => void;
                            • Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback and returns a node-style callback which will resolve or reject the Deferred's promise.

                            class ErrorFactory

                            class ErrorFactory<
                            ErrorCode extends string,
                            ErrorParams extends {
                            readonly [K in ErrorCode]?: ErrorData;
                            } = {}
                            > {}

                              constructor

                              constructor(service: string, serviceName: string, errors: ErrorMap<ErrorCode>);

                                method create

                                create: <K extends ErrorCode>(
                                code: K,
                                ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []
                                ) => FirebaseError;

                                  class FirebaseError

                                  class FirebaseError extends Error {}

                                    constructor

                                    constructor(code: string, message: string, customData?: Record<string, unknown>);

                                      property code

                                      readonly code: string;

                                        property customData

                                        customData?: Record<string, unknown>;

                                          property name

                                          readonly name: string;

                                            class Sha1

                                            class Sha1 {}
                                            • SHA-1 cryptographic hash constructor.

                                              The properties declared here are discussed in the above algorithm document.

                                            constructor

                                            constructor();

                                              property blockSize

                                              blockSize: number;

                                                method compress_

                                                compress_: (buf: number[] | Uint8Array | string, offset?: number) => void;
                                                • Internal compress helper function.

                                                  Parameter buf

                                                  Block to compress.

                                                  Parameter offset

                                                  Offset of the block in the buffer.

                                                method digest

                                                digest: () => number[];
                                                • Modifiers

                                                  • @override

                                                method reset

                                                reset: () => void;

                                                  method update

                                                  update: (bytes?: number[] | Uint8Array | string, length?: number) => void;

                                                    Interfaces

                                                    interface Compat

                                                    interface Compat<T> {}
                                                    • Copyright 2021 Google LLC

                                                      Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

                                                      http://www.apache.org/licenses/LICENSE-2.0

                                                      Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

                                                    interface ErrorData

                                                    interface ErrorData {}

                                                      index signature

                                                      [key: string]: unknown;

                                                        interface Observable

                                                        interface Observable<T> {}

                                                          property subscribe

                                                          subscribe: Subscribe<T>;

                                                            interface Observer

                                                            interface Observer<T> {}

                                                              property complete

                                                              complete: CompleteFn;

                                                                property error

                                                                error: ErrorFn;

                                                                  property next

                                                                  next: NextFn<T>;

                                                                    interface StringLike

                                                                    interface StringLike {}

                                                                      method toString

                                                                      toString: () => string;

                                                                        interface Subscribe

                                                                        interface Subscribe<T> {}
                                                                        • The Subscribe interface has two forms - passing the inline function callbacks, or a object interface with callback properties.

                                                                        call signature

                                                                        (next?: NextFn<T>, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;

                                                                          call signature

                                                                          (observer: PartialObserver<T>): Unsubscribe;

                                                                            Type Aliases

                                                                            type CompleteFn

                                                                            type CompleteFn = () => void;

                                                                              type EmulatorMockTokenOptions

                                                                              type EmulatorMockTokenOptions = (
                                                                              | {
                                                                              user_id: string;
                                                                              }
                                                                              | {
                                                                              sub: string;
                                                                              }
                                                                              ) &
                                                                              Partial<FirebaseIdToken>;

                                                                                type ErrorFn

                                                                                type ErrorFn = (error: Error) => void;

                                                                                  type ErrorMap

                                                                                  type ErrorMap<ErrorCode extends string> = {
                                                                                  readonly [K in ErrorCode]: string;
                                                                                  };
                                                                                  • Standardized Firebase Error.

                                                                                    Usage:

                                                                                    // Typescript string literals for type-safe codes type Err = 'unknown' | 'object-not-found' ;

                                                                                    // Closure enum for type-safe error codes // at-enum {string} var Err = { UNKNOWN: 'unknown', OBJECT_NOT_FOUND: 'object-not-found', }

                                                                                    let errors: Map<Err, string> = { 'generic-error': "Unknown error", 'file-not-found': "Could not find file: {$file}", };

                                                                                    // Type-safe function - must pass a valid error code as param. let error = new ErrorFactory('service', 'Service', errors);

                                                                                    ... throw error.create(Err.GENERIC); ... throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); ... // Service: Could not file file: foo.txt (service/file-not-found).

                                                                                    catch (e) { assert(e.message === "Could not find file: foo.txt."); if (e.code === 'service/file-not-found') { console.log("Could not read file: " + e['file']); } }

                                                                                  type Executor

                                                                                  type Executor<T> = (observer: Observer<T>) => void;

                                                                                    type FirebaseSignInProvider

                                                                                    type FirebaseSignInProvider =
                                                                                    | 'custom'
                                                                                    | 'email'
                                                                                    | 'password'
                                                                                    | 'phone'
                                                                                    | 'anonymous'
                                                                                    | 'google.com'
                                                                                    | 'facebook.com'
                                                                                    | 'github.com'
                                                                                    | 'twitter.com'
                                                                                    | 'microsoft.com'
                                                                                    | 'apple.com';
                                                                                    • Copyright 2021 Google LLC

                                                                                      Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

                                                                                      http://www.apache.org/licenses/LICENSE-2.0

                                                                                      Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

                                                                                    type NextFn

                                                                                    type NextFn<T> = (value: T) => void;
                                                                                    • Copyright 2017 Google LLC

                                                                                      Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

                                                                                      http://www.apache.org/licenses/LICENSE-2.0

                                                                                      Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

                                                                                    type PartialObserver

                                                                                    type PartialObserver<T> = Partial<Observer<T>>;

                                                                                      type Unsubscribe

                                                                                      type Unsubscribe = () => void;

                                                                                        Package Files (20)

                                                                                        Dependencies (1)

                                                                                        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/@firebase/util.

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