HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux ip-172-31-4-197 6.8.0-1036-aws #38~22.04.1-Ubuntu SMP Fri Aug 22 15:44:33 UTC 2025 x86_64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/web.enelar.com.co/node_modules/firebase/firebase-app-check-compat.js.map
{"version":3,"file":"firebase-app-check-compat.js","sources":["../logger/src/logger.ts","../util/src/crypt.ts","../util/src/deferred.ts","../util/src/environment.ts","../util/src/errors.ts","../util/src/json.ts","../util/src/jwt.ts","../util/src/uuid.ts","../util/src/exponential_backoff.ts","../component/src/component.ts","../../node_modules/safevalues/dist/mjs/internals/secrets.js","../../node_modules/safevalues/dist/mjs/internals/string_literal.js","../../node_modules/safevalues/dist/mjs/internals/trusted_types.js","../../node_modules/safevalues/dist/mjs/internals/resource_url_impl.js","../../node_modules/safevalues/dist/mjs/builders/resource_url_builders.js","../../node_modules/safevalues/dist/mjs/dom/globals/window.js","../../node_modules/safevalues/dist/mjs/dom/elements/script.js","../app-check/src/state.ts","../app-check/src/constants.ts","../app-check/src/proactive-refresh.ts","../app-check/src/errors.ts","../app-check/src/util.ts","../app-check/src/client.ts","../app-check/src/indexeddb.ts","../app-check/src/logger.ts","../app-check/src/storage.ts","../app-check/src/debug.ts","../util/src/global.ts","../app-check/src/internal-api.ts","../app-check/src/factory.ts","../app-check/src/recaptcha.ts","../app-check/src/providers.ts","../app-check/src/api.ts","../util/src/compat.ts","../app-check/src/index.ts","../app-check-compat/src/errors.ts","../app-check-compat/src/service.ts","../app-check-compat/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n  | 'debug'\n  | 'verbose'\n  | 'info'\n  | 'warn'\n  | 'error'\n  | 'silent';\n\nexport interface LogOptions {\n  level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n  level: LogLevelString;\n  message: string;\n  args: unknown[];\n  type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n  DEBUG,\n  VERBOSE,\n  INFO,\n  WARN,\n  ERROR,\n  SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n  'debug': LogLevel.DEBUG,\n  'verbose': LogLevel.VERBOSE,\n  'info': LogLevel.INFO,\n  'warn': LogLevel.WARN,\n  'error': LogLevel.ERROR,\n  'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n  loggerInstance: Logger,\n  logType: LogLevel,\n  ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n  [LogLevel.DEBUG]: 'log',\n  [LogLevel.VERBOSE]: 'log',\n  [LogLevel.INFO]: 'info',\n  [LogLevel.WARN]: 'warn',\n  [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n  if (logType < instance.logLevel) {\n    return;\n  }\n  const now = new Date().toISOString();\n  const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n  if (method) {\n    console[method as 'log' | 'info' | 'warn' | 'error'](\n      `[${now}]  ${instance.name}:`,\n      ...args\n    );\n  } else {\n    throw new Error(\n      `Attempted to log a message with an invalid logType (value: ${logType})`\n    );\n  }\n};\n\nexport class Logger {\n  /**\n   * Gives you an instance of a Logger to capture messages according to\n   * Firebase's logging scheme.\n   *\n   * @param name The name that the logs will be associated with\n   */\n  constructor(public name: string) {\n    /**\n     * Capture the current instance for later use\n     */\n    instances.push(this);\n  }\n\n  /**\n   * The log level of the given Logger instance.\n   */\n  private _logLevel = defaultLogLevel;\n\n  get logLevel(): LogLevel {\n    return this._logLevel;\n  }\n\n  set logLevel(val: LogLevel) {\n    if (!(val in LogLevel)) {\n      throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n    }\n    this._logLevel = val;\n  }\n\n  // Workaround for setter/getter having to be the same type.\n  setLogLevel(val: LogLevel | LogLevelString): void {\n    this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n  }\n\n  /**\n   * The main (internal) log handler for the Logger instance.\n   * Can be set to a new function in internal package code but not by user.\n   */\n  private _logHandler: LogHandler = defaultLogHandler;\n  get logHandler(): LogHandler {\n    return this._logHandler;\n  }\n  set logHandler(val: LogHandler) {\n    if (typeof val !== 'function') {\n      throw new TypeError('Value assigned to `logHandler` must be a function');\n    }\n    this._logHandler = val;\n  }\n\n  /**\n   * The optional, additional, user-defined log handler for the Logger instance.\n   */\n  private _userLogHandler: LogHandler | null = null;\n  get userLogHandler(): LogHandler | null {\n    return this._userLogHandler;\n  }\n  set userLogHandler(val: LogHandler | null) {\n    this._userLogHandler = val;\n  }\n\n  /**\n   * The functions below are all based on the `console` interface\n   */\n\n  debug(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n    this._logHandler(this, LogLevel.DEBUG, ...args);\n  }\n  log(...args: unknown[]): void {\n    this._userLogHandler &&\n      this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n    this._logHandler(this, LogLevel.VERBOSE, ...args);\n  }\n  info(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n    this._logHandler(this, LogLevel.INFO, ...args);\n  }\n  warn(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n    this._logHandler(this, LogLevel.WARN, ...args);\n  }\n  error(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n    this._logHandler(this, LogLevel.ERROR, ...args);\n  }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n  instances.forEach(inst => {\n    inst.setLogLevel(level);\n  });\n}\n\nexport function setUserLogHandler(\n  logCallback: LogCallback | null,\n  options?: LogOptions\n): void {\n  for (const instance of instances) {\n    let customLogLevel: LogLevel | null = null;\n    if (options && options.level) {\n      customLogLevel = levelStringToEnum[options.level];\n    }\n    if (logCallback === null) {\n      instance.userLogHandler = null;\n    } else {\n      instance.userLogHandler = (\n        instance: Logger,\n        level: LogLevel,\n        ...args: unknown[]\n      ) => {\n        const message = args\n          .map(arg => {\n            if (arg == null) {\n              return null;\n            } else if (typeof arg === 'string') {\n              return arg;\n            } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n              return arg.toString();\n            } else if (arg instanceof Error) {\n              return arg.message;\n            } else {\n              try {\n                return JSON.stringify(arg);\n              } catch (ignored) {\n                return null;\n              }\n            }\n          })\n          .filter(arg => arg)\n          .join(' ');\n        if (level >= (customLogLevel ?? instance.logLevel)) {\n          logCallback({\n            level: LogLevel[level].toLowerCase() as LogLevelString,\n            message,\n            args,\n            type: instance.name\n          });\n        }\n      };\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n  // TODO(user): Use native implementations if/when available\n  const out: number[] = [];\n  let p = 0;\n  for (let i = 0; i < str.length; i++) {\n    let c = str.charCodeAt(i);\n    if (c < 128) {\n      out[p++] = c;\n    } else if (c < 2048) {\n      out[p++] = (c >> 6) | 192;\n      out[p++] = (c & 63) | 128;\n    } else if (\n      (c & 0xfc00) === 0xd800 &&\n      i + 1 < str.length &&\n      (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n    ) {\n      // Surrogate Pair\n      c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n      out[p++] = (c >> 18) | 240;\n      out[p++] = ((c >> 12) & 63) | 128;\n      out[p++] = ((c >> 6) & 63) | 128;\n      out[p++] = (c & 63) | 128;\n    } else {\n      out[p++] = (c >> 12) | 224;\n      out[p++] = ((c >> 6) & 63) | 128;\n      out[p++] = (c & 63) | 128;\n    }\n  }\n  return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n  // TODO(user): Use native implementations if/when available\n  const out: string[] = [];\n  let pos = 0,\n    c = 0;\n  while (pos < bytes.length) {\n    const c1 = bytes[pos++];\n    if (c1 < 128) {\n      out[c++] = String.fromCharCode(c1);\n    } else if (c1 > 191 && c1 < 224) {\n      const c2 = bytes[pos++];\n      out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n    } else if (c1 > 239 && c1 < 365) {\n      // Surrogate Pair\n      const c2 = bytes[pos++];\n      const c3 = bytes[pos++];\n      const c4 = bytes[pos++];\n      const u =\n        (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n        0x10000;\n      out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n      out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n    } else {\n      const c2 = bytes[pos++];\n      const c3 = bytes[pos++];\n      out[c++] = String.fromCharCode(\n        ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n      );\n    }\n  }\n  return out.join('');\n};\n\ninterface Base64 {\n  byteToCharMap_: { [key: number]: string } | null;\n  charToByteMap_: { [key: string]: number } | null;\n  byteToCharMapWebSafe_: { [key: number]: string } | null;\n  charToByteMapWebSafe_: { [key: string]: number } | null;\n  ENCODED_VALS_BASE: string;\n  readonly ENCODED_VALS: string;\n  readonly ENCODED_VALS_WEBSAFE: string;\n  HAS_NATIVE_SUPPORT: boolean;\n  encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n  encodeString(input: string, webSafe?: boolean): string;\n  decodeString(input: string, webSafe: boolean): string;\n  decodeStringToByteArray(input: string, webSafe: boolean): number[];\n  init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\nexport const base64: Base64 = {\n  /**\n   * Maps bytes to characters.\n   */\n  byteToCharMap_: null,\n\n  /**\n   * Maps characters to bytes.\n   */\n  charToByteMap_: null,\n\n  /**\n   * Maps bytes to websafe characters.\n   * @private\n   */\n  byteToCharMapWebSafe_: null,\n\n  /**\n   * Maps websafe characters to bytes.\n   * @private\n   */\n  charToByteMapWebSafe_: null,\n\n  /**\n   * Our default alphabet, shared between\n   * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n   */\n  ENCODED_VALS_BASE:\n    'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n  /**\n   * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n   */\n  get ENCODED_VALS() {\n    return this.ENCODED_VALS_BASE + '+/=';\n  },\n\n  /**\n   * Our websafe alphabet.\n   */\n  get ENCODED_VALS_WEBSAFE() {\n    return this.ENCODED_VALS_BASE + '-_.';\n  },\n\n  /**\n   * Whether this browser supports the atob and btoa functions. This extension\n   * started at Mozilla but is now implemented by many browsers. We use the\n   * ASSUME_* variables to avoid pulling in the full useragent detection library\n   * but still allowing the standard per-browser compilations.\n   *\n   */\n  HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n  /**\n   * Base64-encode an array of bytes.\n   *\n   * @param input An array of bytes (numbers with\n   *     value in [0, 255]) to encode.\n   * @param webSafe Boolean indicating we should use the\n   *     alternative alphabet.\n   * @return The base64 encoded string.\n   */\n  encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n    if (!Array.isArray(input)) {\n      throw Error('encodeByteArray takes an array as a parameter');\n    }\n\n    this.init_();\n\n    const byteToCharMap = webSafe\n      ? this.byteToCharMapWebSafe_!\n      : this.byteToCharMap_!;\n\n    const output = [];\n\n    for (let i = 0; i < input.length; i += 3) {\n      const byte1 = input[i];\n      const haveByte2 = i + 1 < input.length;\n      const byte2 = haveByte2 ? input[i + 1] : 0;\n      const haveByte3 = i + 2 < input.length;\n      const byte3 = haveByte3 ? input[i + 2] : 0;\n\n      const outByte1 = byte1 >> 2;\n      const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n      let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n      let outByte4 = byte3 & 0x3f;\n\n      if (!haveByte3) {\n        outByte4 = 64;\n\n        if (!haveByte2) {\n          outByte3 = 64;\n        }\n      }\n\n      output.push(\n        byteToCharMap[outByte1],\n        byteToCharMap[outByte2],\n        byteToCharMap[outByte3],\n        byteToCharMap[outByte4]\n      );\n    }\n\n    return output.join('');\n  },\n\n  /**\n   * Base64-encode a string.\n   *\n   * @param input A string to encode.\n   * @param webSafe If true, we should use the\n   *     alternative alphabet.\n   * @return The base64 encoded string.\n   */\n  encodeString(input: string, webSafe?: boolean): string {\n    // Shortcut for Mozilla browsers that implement\n    // a native base64 encoder in the form of \"btoa/atob\"\n    if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n      return btoa(input);\n    }\n    return this.encodeByteArray(stringToByteArray(input), webSafe);\n  },\n\n  /**\n   * Base64-decode a string.\n   *\n   * @param input to decode.\n   * @param webSafe True if we should use the\n   *     alternative alphabet.\n   * @return string representing the decoded value.\n   */\n  decodeString(input: string, webSafe: boolean): string {\n    // Shortcut for Mozilla browsers that implement\n    // a native base64 encoder in the form of \"btoa/atob\"\n    if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n      return atob(input);\n    }\n    return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n  },\n\n  /**\n   * Base64-decode a string.\n   *\n   * In base-64 decoding, groups of four characters are converted into three\n   * bytes.  If the encoder did not apply padding, the input length may not\n   * be a multiple of 4.\n   *\n   * In this case, the last group will have fewer than 4 characters, and\n   * padding will be inferred.  If the group has one or two characters, it decodes\n   * to one byte.  If the group has three characters, it decodes to two bytes.\n   *\n   * @param input Input to decode.\n   * @param webSafe True if we should use the web-safe alphabet.\n   * @return bytes representing the decoded value.\n   */\n  decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n    this.init_();\n\n    const charToByteMap = webSafe\n      ? this.charToByteMapWebSafe_!\n      : this.charToByteMap_!;\n\n    const output: number[] = [];\n\n    for (let i = 0; i < input.length; ) {\n      const byte1 = charToByteMap[input.charAt(i++)];\n\n      const haveByte2 = i < input.length;\n      const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n      ++i;\n\n      const haveByte3 = i < input.length;\n      const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n      ++i;\n\n      const haveByte4 = i < input.length;\n      const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n      ++i;\n\n      if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n        throw new DecodeBase64StringError();\n      }\n\n      const outByte1 = (byte1 << 2) | (byte2 >> 4);\n      output.push(outByte1);\n\n      if (byte3 !== 64) {\n        const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n        output.push(outByte2);\n\n        if (byte4 !== 64) {\n          const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n          output.push(outByte3);\n        }\n      }\n    }\n\n    return output;\n  },\n\n  /**\n   * Lazy static initialization function. Called before\n   * accessing any of the static map variables.\n   * @private\n   */\n  init_() {\n    if (!this.byteToCharMap_) {\n      this.byteToCharMap_ = {};\n      this.charToByteMap_ = {};\n      this.byteToCharMapWebSafe_ = {};\n      this.charToByteMapWebSafe_ = {};\n\n      // We want quick mappings back and forth, so we precompute two maps.\n      for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n        this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n        this.charToByteMap_[this.byteToCharMap_[i]] = i;\n        this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n        this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n        // Be forgiving when decoding and correctly decode both encodings.\n        if (i >= this.ENCODED_VALS_BASE.length) {\n          this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n          this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n        }\n      }\n    }\n  }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n  readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n  const utf8Bytes = stringToByteArray(str);\n  return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n  // Use base64url encoding and remove padding in the end (dot characters).\n  return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n  try {\n    return base64.decodeString(str, true);\n  } catch (e) {\n    console.error('base64Decode failed: ', e);\n  }\n  return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<R> {\n  promise: Promise<R>;\n  reject: (value?: unknown) => void = () => {};\n  resolve: (value?: unknown) => void = () => {};\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = resolve as (value?: unknown) => void;\n      this.reject = reject as (value?: unknown) => void;\n    });\n  }\n\n  /**\n   * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\n   * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n   * and returns a node-style callback which will resolve or reject the Deferred's promise.\n   */\n  wrapCallback(\n    callback?: (error?: unknown, value?: unknown) => void\n  ): (error: unknown, value?: unknown) => void {\n    return (error, value?) => {\n      if (error) {\n        this.reject(error);\n      } else {\n        this.resolve(value);\n      }\n      if (typeof callback === 'function') {\n        // Attaching noop handler just in case developer wasn't expecting\n        // promises\n        this.promise.catch(() => {});\n\n        // Some of our callbacks don't expect a value and our own tests\n        // assert that the parameter length is 1\n        if (callback.length === 1) {\n          callback(error);\n        } else {\n          callback(error, value);\n        }\n      }\n    };\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Type placeholder for `WorkerGlobalScope` from `webworker`\n */\ndeclare class WorkerGlobalScope {}\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n  if (\n    typeof navigator !== 'undefined' &&\n    typeof navigator['userAgent'] === 'string'\n  ) {\n    return navigator['userAgent'];\n  } else {\n    return '';\n  }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n  return (\n    typeof window !== 'undefined' &&\n    // @ts-ignore Setting up an broadly applicable index signature for Window\n    // just to deal with this case would probably be a bad idea.\n    !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n    /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n  );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n  const forceEnvironment = getDefaults()?.forceEnvironment;\n  if (forceEnvironment === 'node') {\n    return true;\n  } else if (forceEnvironment === 'browser') {\n    return false;\n  }\n\n  try {\n    return (\n      Object.prototype.toString.call(global.process) === '[object process]'\n    );\n  } catch (e) {\n    return false;\n  }\n}\n\n/**\n * Detect Browser Environment\n */\nexport function isBrowser(): boolean {\n  return typeof window !== 'undefined' || isWebWorker();\n}\n\n/**\n * Detect Web Worker context\n */\nexport function isWebWorker(): boolean {\n  return (\n    typeof WorkerGlobalScope !== 'undefined' &&\n    typeof self !== 'undefined' &&\n    self instanceof WorkerGlobalScope\n  );\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n  id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n  const runtime =\n    typeof chrome === 'object'\n      ? chrome.runtime\n      : typeof browser === 'object'\n      ? browser.runtime\n      : undefined;\n  return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n  return (\n    typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n  );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n  return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n  const ua = getUA();\n  return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n  return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n  return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n  return (\n    !isNode() &&\n    !!navigator.userAgent &&\n    navigator.userAgent.includes('Safari') &&\n    !navigator.userAgent.includes('Chrome')\n  );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n  try {\n    return typeof indexedDB === 'object';\n  } catch (e) {\n    return false;\n  }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise<boolean> {\n  return new Promise((resolve, reject) => {\n    try {\n      let preExist: boolean = true;\n      const DB_CHECK_NAME =\n        'validate-browser-context-for-indexeddb-analytics-module';\n      const request = self.indexedDB.open(DB_CHECK_NAME);\n      request.onsuccess = () => {\n        request.result.close();\n        // delete database only when it doesn't pre-exist\n        if (!preExist) {\n          self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n        }\n        resolve(true);\n      };\n      request.onupgradeneeded = () => {\n        preExist = false;\n      };\n\n      request.onerror = () => {\n        reject(request.error?.message || '');\n      };\n    } catch (error) {\n      reject(error);\n    }\n  });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n  if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n    return false;\n  }\n  return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n *   // Typescript string literals for type-safe codes\n *   type Err =\n *     'unknown' |\n *     'object-not-found'\n *     ;\n *\n *   // Closure enum for type-safe error codes\n *   // at-enum {string}\n *   var Err = {\n *     UNKNOWN: 'unknown',\n *     OBJECT_NOT_FOUND: 'object-not-found',\n *   }\n *\n *   let errors: Map<Err, string> = {\n *     'generic-error': \"Unknown error\",\n *     'file-not-found': \"Could not find file: {$file}\",\n *   };\n *\n *   // Type-safe function - must pass a valid error code as param.\n *   let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n *   ...\n *   throw error.create(Err.GENERIC);\n *   ...\n *   throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n *   ...\n *   // Service: Could not file file: foo.txt (service/file-not-found).\n *\n *   catch (e) {\n *     assert(e.message === \"Could not find file: foo.txt.\");\n *     if ((e as FirebaseError)?.code === 'service/file-not-found') {\n *       console.log(\"Could not read file: \" + e['file']);\n *     }\n *   }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n  readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n  toString(): string;\n}\n\nexport interface ErrorData {\n  [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n  /** The custom name for all FirebaseErrors. */\n  readonly name: string = ERROR_NAME;\n\n  constructor(\n    /** The error code for this error. */\n    readonly code: string,\n    message: string,\n    /** Custom data for this error. */\n    public customData?: Record<string, unknown>\n  ) {\n    super(message);\n\n    // Fix For ES5\n    // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n    Object.setPrototypeOf(this, FirebaseError.prototype);\n\n    // Maintains proper stack trace for where our error was thrown.\n    // Only available on V8.\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, ErrorFactory.prototype.create);\n    }\n  }\n}\n\nexport class ErrorFactory<\n  ErrorCode extends string,\n  ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n  constructor(\n    private readonly service: string,\n    private readonly serviceName: string,\n    private readonly errors: ErrorMap<ErrorCode>\n  ) {}\n\n  create<K extends ErrorCode>(\n    code: K,\n    ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n  ): FirebaseError {\n    const customData = (data[0] as ErrorData) || {};\n    const fullCode = `${this.service}/${code}`;\n    const template = this.errors[code];\n\n    const message = template ? replaceTemplate(template, customData) : 'Error';\n    // Service Name: Error message (service/code).\n    const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n    const error = new FirebaseError(fullCode, fullMessage, customData);\n\n    return error;\n  }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n  return template.replace(PATTERN, (_, key) => {\n    const value = data[key];\n    return value != null ? String(value) : `<${key}?>`;\n  });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n  return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data Javascript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n  return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n  [key: string]: {};\n}\n\ninterface DecodedToken {\n  header: object;\n  claims: Claims;\n  data: object;\n  signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n  let header = {},\n    claims: Claims = {},\n    data = {},\n    signature = '';\n\n  try {\n    const parts = token.split('.');\n    header = jsonEval(base64Decode(parts[0]) || '') as object;\n    claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n    signature = parts[2];\n    data = claims['d'] || {};\n    delete claims['d'];\n  } catch (e) {}\n\n  return {\n    header,\n    claims,\n    data,\n    signature\n  };\n};\n\ninterface DecodedToken {\n  header: object;\n  claims: Claims;\n  data: object;\n  signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n  const claims: Claims = decode(token).claims;\n  const now: number = Math.floor(new Date().getTime() / 1000);\n  let validSince: number = 0,\n    validUntil: number = 0;\n\n  if (typeof claims === 'object') {\n    if (claims.hasOwnProperty('nbf')) {\n      validSince = claims['nbf'] as number;\n    } else if (claims.hasOwnProperty('iat')) {\n      validSince = claims['iat'] as number;\n    }\n\n    if (claims.hasOwnProperty('exp')) {\n      validUntil = claims['exp'] as number;\n    } else {\n      // token will expire after 24h by default\n      validUntil = validSince + 86400;\n    }\n  }\n\n  return (\n    !!now &&\n    !!validSince &&\n    !!validUntil &&\n    now >= validSince &&\n    now <= validUntil\n  );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n  const claims: Claims = decode(token).claims;\n  if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n    return claims['iat'] as number;\n  }\n  return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n  const decoded = decode(token),\n    claims = decoded.claims;\n\n  return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n  const claims: Claims = decode(token).claims;\n  return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Copied from https://stackoverflow.com/a/2117523\n * Generates a new uuid.\n * @public\n */\nexport const uuidv4 = function (): string {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n    const r = (Math.random() * 16) | 0,\n      v = c === 'x' ? r : (r & 0x3) | 0x8;\n    return v.toString(16);\n  });\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n * <p>Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n * <p>Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n  backoffCount: number,\n  intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n  backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n  // Calculates an exponentially increasing value.\n  // Deviation: calculates value from count and a constant interval, so we only need to save value\n  // and count to restore state.\n  const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n  // A random \"fuzz\" to avoid waves of retries.\n  // Deviation: randomFactor is required.\n  const randomWait = Math.round(\n    // A fraction of the backoff value to add/subtract.\n    // Deviation: changes multiplication order to improve readability.\n    RANDOM_FACTOR *\n      currBaseValue *\n      // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n      // if we add or subtract.\n      (Math.random() - 0.5) *\n      2\n  );\n\n  // Limits backoff to max to avoid effectively permanent backoff.\n  return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n  InstantiationMode,\n  InstanceFactory,\n  ComponentType,\n  Dictionary,\n  Name,\n  onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n  multipleInstances = false;\n  /**\n   * Properties to be added to the service namespace\n   */\n  serviceProps: Dictionary = {};\n\n  instantiationMode = InstantiationMode.LAZY;\n\n  onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n  /**\n   *\n   * @param name The public service name, e.g. app, auth, firestore, database\n   * @param instanceFactory Service factory responsible for creating the public interface\n   * @param type whether the service provided by the component is public or private\n   */\n  constructor(\n    readonly name: T,\n    readonly instanceFactory: InstanceFactory<T>,\n    readonly type: ComponentType\n  ) {}\n\n  setInstantiationMode(mode: InstantiationMode): this {\n    this.instantiationMode = mode;\n    return this;\n  }\n\n  setMultipleInstances(multipleInstances: boolean): this {\n    this.multipleInstances = multipleInstances;\n    return this;\n  }\n\n  setServiceProps(props: Dictionary): this {\n    this.serviceProps = props;\n    return this;\n  }\n\n  setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n    this.onInstanceCreated = callback;\n    return this;\n  }\n}\n","/**\n * @license\n * SPDX-License-Identifier: Apache-2.0\n */\nimport '../environment/dev.js';\n/**\n * A secret token that must be passed to safe type constructors. It is only\n * accessible from within safevalues, ensuring that unrestricted safe type\n * creation is only possible within safevalues. In particular, this prevents\n * forgery such as `safeHtmlValue.constructor('javascript:evil')`.\n */\nexport const secretToken = {};\n/**\n * Asserts that the given token matches the secret safevalues token. An\n * exception is thrown if that is not the case.\n */\nexport function ensureTokenIsValid(token) {\n    if (process.env.NODE_ENV !== 'production') {\n        if (token !== secretToken) {\n            throw new Error('Bad secret');\n        }\n    }\n}\n","/**\n * @license\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * An object of type TemplateStringsArray represents the literal part(s) of a\n * template literal. This function checks if a TemplateStringsArray object is\n * actually from a template literal.\n *\n * @param templateObj This contains the literal part of the template literal.\n * @param numExprs The number of embedded expressions\n */\nexport function assertIsTemplateObject(templateObj, numExprs) {\n    if (!isTemplateObject(templateObj) || numExprs + 1 !== templateObj.length) {\n        throw new TypeError(`\n    ############################## ERROR ##############################\n\n    It looks like you are trying to call a template tag function (fn\\`...\\`)\n    using the normal function syntax (fn(...)), which is not supported.\n\n    The functions in the safevalues library are not designed to be called\n    like normal functions, and doing so invalidates the security guarantees\n    that safevalues provides.\n\n    If you are stuck and not sure how to proceed, please reach out to us\n    instead through:\n     - https://github.com/google/safevalues/issues\n\n    ############################## ERROR ##############################`);\n    }\n}\n/** Checks if `templateObj` and its raw property are frozen. */\nfunction checkFrozen(templateObj) {\n    return Object.isFrozen(templateObj) && Object.isFrozen(templateObj.raw);\n}\n/**\n * Checks if a function containing a tagged template expression is transpiled.\n */\nfunction checkTranspiled(fn) {\n    return fn.toString().indexOf('`') === -1;\n}\n/**\n * This value tells us if the code is transpiled, in which case we don't\n * check certain things that transpilers typically don't support. The\n * transpilation turns it into a function call that takes an array.\n */\nconst isTranspiled = checkTranspiled((tag) => tag ``) ||\n    checkTranspiled((tag) => tag `\\0`) ||\n    checkTranspiled((tag) => tag `\\n`) ||\n    checkTranspiled((tag) => tag `\\u0000`);\n/**\n * This value tells us if `TemplateStringsArray` are typically frozen in the\n * current environment.\n */\nconst frozenTSA = checkFrozen `` && checkFrozen `\\0` && checkFrozen `\\n` && checkFrozen `\\u0000`;\n/** Polyfill of https://github.com/tc39/proposal-array-is-template-object */\nfunction isTemplateObject(templateObj) {\n    /*\n     * ############################## WARNING ##############################\n     *\n     * If you are reading this code to understand how to create a value\n     * that satisfies this check, STOP and read this paragraph.\n     *\n     * This function is there to ensure that our tagged template functions are\n     * always called using the tag syntax fn`...`, rather than the normal\n     * function syntax fn(...). Bypassing this check invalidates the guarantees\n     * that safevalues provides and will result in security issues in your code.\n     *\n     * If you are stuck and not sure how to proceed, please reach out to us\n     * instead through:\n     *  - https://github.com/google/safevalues/issues\n     *\n     * ############################## WARNING ##############################\n     */\n    if (!Array.isArray(templateObj) || !Array.isArray(templateObj.raw)) {\n        return false;\n    }\n    if (templateObj.length !== templateObj.raw.length) {\n        return false;\n    }\n    if (!isTranspiled && templateObj === templateObj.raw) {\n        // Sometimes transpilers use the same array to save on codesize if the\n        // template has no special characters that would cause the values in each\n        // array to be different.\n        return false;\n    }\n    if ((!isTranspiled || frozenTSA) && !checkFrozen(templateObj)) {\n        // Transpilers typically don't freeze `TemplateStringsArray` objects, but we\n        // expect that if they did, they would do it consistently, so we also\n        // dynamically check if they do.\n        return false;\n    }\n    return true;\n}\n","/**\n * @license\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * The name of the Trusted Types policy used by TS safevalues, or empty\n * to disable Trusted Types. This duplicates the 'google#safe', but\n * can be overridden in tests.\n */\nlet trustedTypesPolicyName = 'google#safe';\n/** Helper to retrieve the value of `window.trustedTypes`. */\nfunction trustedTypes() {\n    if (typeof window !== 'undefined') {\n        return window.trustedTypes;\n    }\n    return undefined;\n}\n/**\n * Returns window.trustedTypes if Trusted Types are enabled and supported, or\n * null otherwise.\n */\nexport function getTrustedTypes() {\n    var _a;\n    return trustedTypesPolicyName !== '' ? (_a = trustedTypes()) !== null && _a !== void 0 ? _a : null : null;\n}\n/**\n * The Trusted Types policy used by TS safevalues, or null if Trusted Types\n * are not enabled/supported, or undefined if the policy has not been created\n * yet.\n */\nlet trustedTypesPolicy;\n/**\n * Returns the Trusted Types policy used by TS safevalues, or null if Trusted\n * Types are not enabled/supported. The first call to this function will\n * create the policy.\n */\nexport function getTrustedTypesPolicy() {\n    var _a, _b;\n    if (trustedTypesPolicy === undefined) {\n        try {\n            trustedTypesPolicy =\n                (_b = (_a = getTrustedTypes()) === null || _a === void 0 ? void 0 : _a.createPolicy(trustedTypesPolicyName, {\n                    createHTML: (s) => s,\n                    createScript: (s) => s,\n                    createScriptURL: (s) => s,\n                })) !== null && _b !== void 0 ? _b : null;\n        }\n        catch (_c) {\n            // In Chromium versions before 81, trustedTypes.createPolicy throws if\n            // called with a name that is already registered, even if no CSP is set.\n            // Until users have largely migrated to 81 or above, catch the error not\n            // to break the applications functionally. In such case, the code will\n            // fall back to using regular Safe Types.\n            trustedTypesPolicy = null;\n        }\n    }\n    return trustedTypesPolicy;\n}\n/** Helpers for tests. */\nexport const TEST_ONLY = {\n    resetDefaults() {\n        trustedTypesPolicy = undefined;\n        trustedTypesPolicyName = 'google#safe';\n    },\n    setTrustedTypesPolicyName(name) {\n        trustedTypesPolicyName = name;\n    },\n};\n","/**\n * @license\n * SPDX-License-Identifier: Apache-2.0\n */\nimport '../environment/dev.js';\nimport { ensureTokenIsValid, secretToken } from './secrets.js';\nimport { getTrustedTypes, getTrustedTypesPolicy } from './trusted_types.js';\n/**\n * Runtime implementation of `TrustedScriptURL` in browsers that don't support\n * it.\n */\nclass ResourceUrlImpl {\n    constructor(url, token) {\n        ensureTokenIsValid(token);\n        this.privateDoNotAccessOrElseWrappedResourceUrl = url;\n    }\n    toString() {\n        return this.privateDoNotAccessOrElseWrappedResourceUrl.toString();\n    }\n}\nconst GlobalTrustedScriptURL = typeof window !== 'undefined' ? window.TrustedScriptURL : undefined;\n/**\n * Also exports the constructor so that instanceof checks work.\n */\nexport const TrustedResourceUrl = (GlobalTrustedScriptURL !== null && GlobalTrustedScriptURL !== void 0 ? GlobalTrustedScriptURL : ResourceUrlImpl);\n/**\n * Builds a new `TrustedResourceUrl` from the given string, without\n * enforcing safety guarantees. It may cause side effects by creating a Trusted\n * Types policy. This shouldn't be exposed to application developers, and must\n * only be used as a step towards safe builders or safe constants.\n */\nexport function createResourceUrlInternal(url) {\n    var _a;\n    /** @noinline */\n    const noinlineUrl = url;\n    const trustedScriptURL = (_a = getTrustedTypesPolicy()) === null || _a === void 0 ? void 0 : _a.createScriptURL(noinlineUrl);\n    return (trustedScriptURL !== null && trustedScriptURL !== void 0 ? trustedScriptURL : new ResourceUrlImpl(noinlineUrl, secretToken));\n}\n/**\n * Checks if the given value is a `TrustedResourceUrl` instance.\n */\nexport function isResourceUrl(value) {\n    var _a;\n    return (((_a = getTrustedTypes()) === null || _a === void 0 ? void 0 : _a.isScriptURL(value)) || value instanceof ResourceUrlImpl);\n}\n/**\n * Returns the value of the passed `TrustedResourceUrl` object while ensuring it\n * has the correct type.\n *\n * Returns a native `TrustedScriptURL` or a string if Trusted Types are\n * disabled.\n */\nexport function unwrapResourceUrl(value) {\n    var _a;\n    if ((_a = getTrustedTypes()) === null || _a === void 0 ? void 0 : _a.isScriptURL(value)) {\n        return value;\n    }\n    else if (value instanceof ResourceUrlImpl) {\n        return value.privateDoNotAccessOrElseWrappedResourceUrl;\n    }\n    else {\n        let message = '';\n        if (process.env.NODE_ENV !== 'production') {\n            message = 'Unexpected type when unwrapping TrustedResourceUrl';\n        }\n        throw new Error(message);\n    }\n}\n","/**\n * @license\n * SPDX-License-Identifier: Apache-2.0\n */\nimport '../environment/dev.js';\nimport { createResourceUrlInternal, unwrapResourceUrl, } from '../internals/resource_url_impl.js';\nimport { unwrapScript } from '../internals/script_impl.js';\nimport { assertIsTemplateObject } from '../internals/string_literal.js';\n/**\n * Check whether the base url contains a valid origin,\n *\n * A string for an origin must contain only alphanumeric or any of the\n * following: `-.:`, and must not be an IP address. Remember that, as per the\n * documentation for TrustedResourceUrl, the origin must be trustworthy.\n *\n * @param base The base url that contains an origin.\n */\nfunction hasValidOrigin(base) {\n    if (!(/^https:\\/\\//.test(base) || /^\\/\\//.test(base))) {\n        return false;\n    }\n    const originStart = base.indexOf('//') + 2;\n    const originEnd = base.indexOf('/', originStart);\n    // If the base url only contains the prefix (e.g. //), or the slash\n    // for the origin is right after the prefix (e.g. ///), the origin is\n    // missing.\n    if (originEnd <= originStart) {\n        throw new Error(`Can't interpolate data in a url's origin, ` +\n            `Please make sure to fully specify the origin, terminated with '/'.`);\n    }\n    const origin = base.substring(originStart, originEnd);\n    if (!/^[0-9a-z.:-]+$/i.test(origin)) {\n        throw new Error('The origin contains unsupported characters.');\n    }\n    if (!/^[^:]*(:[0-9]+)?$/i.test(origin)) {\n        throw new Error('Invalid port number.');\n    }\n    if (!/(^|\\.)[a-z][^.]*$/i.test(origin)) {\n        throw new Error('The top-level domain must start with a letter.');\n    }\n    return true;\n}\n/**\n * Check whether the base url contains a valid about url at its beginning.\n *\n * An about url is either exactly 'about:blank' or 'about:blank#<str>' where\n * <str> can be an arbitrary string.\n *\n * @param base The base url.\n */\nfunction isValidAboutUrl(base) {\n    if (!/^about:blank/.test(base)) {\n        return false;\n    }\n    if (base !== 'about:blank' && !/^about:blank#/.test(base)) {\n        throw new Error('The about url is invalid.');\n    }\n    return true;\n}\n/**\n * Check whether the base url contains a valid path start at its beginning.\n *\n * A valid path start is either a '/' or a '/' followed by at least one\n * character that is not '/' or '\\'.\n *\n * @param base The base url.\n */\nfunction isValidPathStart(base) {\n    if (!/^\\//.test(base)) {\n        return false;\n    }\n    if (base === '/' ||\n        (base.length > 1 && base[1] !== '/' && base[1] !== '\\\\')) {\n        return true;\n    }\n    throw new Error('The path start in the url is invalid.');\n}\n/**\n * Check whether the base url contains a valid relative path start at its\n * beginning.\n *\n * A valid relative path start is a non empty string that has no ':', '/' nor\n * '\\', and that is followed by a '/'.\n *\n * @param base The base url.\n */\nfunction isValidRelativePathStart(base) {\n    // Using the RegExp syntax as the native JS RegExp syntax is not well handled\n    // by some downstream bundlers with this regex.\n    return new RegExp('^[^:\\\\s\\\\\\\\/]+/').test(base);\n}\n/**\n * Splits an url into segments using '?' and '#' delimiters.\n *\n * The URL can later be put back together by concatenating the returned segments\n * like: path + params + hash. Note that the delimiters '?' and '#' will\n * already be included in 'params' and 'hash' values respectively when these are\n * not empty.\n *\n * @param url The url to split.\n */\nfunction getUrlSegments(url) {\n    const segments = url.split(/\\?|#/);\n    const params = /\\?/.test(url) ? '?' + segments[1] : '';\n    const hash = /#/.test(url) ? '#' + (params ? segments[2] : segments[1]) : '';\n    return { path: segments[0], params, hash };\n}\n/**\n * Builds TrustedResourceUrl from a template literal.\n *\n * This factory is a template literal tag function. It should be called with\n * a template literal, with or without embedded expressions. For example,\n *               trustedResourceUrl`//example.com/${bar}`;\n * or\n *               trustedResourceUrl`//example.com`;\n *\n * When this function is called with a template literal without any embedded\n * expressions, the template string may contain anything as the whole URL is\n * a compile-time string constant.\n *\n * When this function is called with a template literal that contains embedded\n * expressions, the template must start with one of the following:\n * - `https://<origin>/`\n * - `//<origin>/`\n * - `/<pathStart>`\n * - `<relativePathStart>/`\n * - `about:blank`\n * - `data:`\n *\n * `<origin>` must contain only alphanumeric or any of the following: `-.:`.\n * Remember that, as per the documentation for TrustedResourceUrl, the origin\n * must be trustworthy. An origin of \"example.com\" could be set with this\n * method, but would tie the security of your site to the security of\n * example.com. Similarly, formats that potentially cover redirects hosted\n * on a trusted origin are problematic, since that could lead to untrusted\n * origins.\n *\n * `<pathStart>` is either an empty string, or a non empty string that does not\n * start with '/' or '\\'.\n * In other words, `/<pathStart>` is either a '/' or a\n * '/' followed by at least one character that is not '/' or '\\'.\n *\n * `<relativePathStart> is a non empty string that has no ':', '/' nor '\\'.\n *\n * `data:` (data URL) does not allow embedded expressions in the template\n * literal input.\n *\n * All embedded expressions are URL encoded when they are interpolated. Do not\n * embed expressions that are already URL encoded as they will be double encoded\n * by the builder.\n *\n * @param templateObj This contains the literal part of the template literal.\n * @param rest This represents the template's embedded expressions.\n */\nexport function trustedResourceUrl(templateObj, ...rest) {\n    // Check if templateObj is actually from a template literal.\n    if (process.env.NODE_ENV !== 'production') {\n        assertIsTemplateObject(templateObj, rest.length);\n    }\n    if (rest.length === 0) {\n        return createResourceUrlInternal(templateObj[0]);\n    }\n    const base = templateObj[0].toLowerCase();\n    if (process.env.NODE_ENV !== 'production') {\n        if (/^data:/.test(base)) {\n            throw new Error('Data URLs cannot have expressions in the template literal input.');\n        }\n        if (!hasValidOrigin(base) &&\n            !isValidPathStart(base) &&\n            !isValidRelativePathStart(base) &&\n            !isValidAboutUrl(base)) {\n            throw new Error('Trying to interpolate expressions in an unsupported url format.');\n        }\n    }\n    let url = templateObj[0];\n    for (let i = 0; i < rest.length; i++) {\n        url += encodeURIComponent(rest[i]) + templateObj[i + 1];\n    }\n    return createResourceUrlInternal(url);\n}\n/**\n * Creates a new TrustedResourceUrl with params added to the URL's search\n * parameters.\n *\n * @param params What to add to the URL. Parameters with value `null` or\n * `undefined` are skipped. Both keys and values will be encoded. Do not pass\n * pre-encoded values as this will result them being double encoded. If the\n * value is an array then the same parameter is added for every element in the\n * array.\n */\nexport function appendParams(trustedUrl, params) {\n    const urlSegments = getUrlSegments(unwrapResourceUrl(trustedUrl).toString());\n    let urlParams = urlSegments.params;\n    let separator = urlParams.length ? '&' : '?';\n    // for-of has a big polyfill.\n    // tslint:disable-next-line:ban-iterable-foreach\n    params.forEach((value, key) => {\n        const values = value instanceof Array ? value : [value];\n        for (let i = 0; i < values.length; i++) {\n            const v = values[i];\n            if (v === null || v === undefined) {\n                continue;\n            }\n            urlParams +=\n                separator +\n                    encodeURIComponent(key) +\n                    '=' +\n                    encodeURIComponent(String(v));\n            separator = '&';\n        }\n    });\n    return createResourceUrlInternal(urlSegments.path + urlParams + urlSegments.hash);\n}\nconst BEFORE_FRAGMENT_REGEXP = /[^#]*/;\n/**\n * Creates a new TrustedResourceUrl based on an existing one but with the\n * addition of a fragment (the part after `#`). If the URL already has a\n * fragment, it is replaced with the new one.\n * @param fragment The fragment to add to the URL, verbatim, without the leading\n * `#`. No additional escaping is applied.\n */\nexport function replaceFragment(trustedUrl, fragment) {\n    const urlString = unwrapResourceUrl(trustedUrl).toString();\n    return createResourceUrlInternal(BEFORE_FRAGMENT_REGEXP.exec(urlString)[0] + '#' + fragment);\n}\n/**\n * Creates a new TrustedResourceUrl based on an existing one with a single\n * subpath segment added to the end of the existing path and prior to any query\n * parameters and/or fragments that already exist in the URL.\n * @param pathSegment The singular sub path being added to the URL. Do not pass\n *     a pre-encoded value as this will result in it being double encoded.\n */\nexport function appendPathSegment(trustedUrl, pathSegment) {\n    const urlSegments = getUrlSegments(unwrapResourceUrl(trustedUrl).toString());\n    const separator = urlSegments.path.slice(-1) === '/' ? '' : '/';\n    const newPath = urlSegments.path + separator + encodeURIComponent(pathSegment);\n    return createResourceUrlInternal(newPath + urlSegments.params + urlSegments.hash);\n}\n/**\n * Creates a `TrustedResourceUrl` by generating a `Blob` from a\n * `SafeScript` and then calling `URL.createObjectURL` with that `Blob`.\n *\n * Caller must call `URL.revokeObjectURL()` on the stringified url to\n * release the underlying `Blob`.\n */\nexport function objectUrlFromScript(safeScript) {\n    const scriptContent = unwrapScript(safeScript).toString();\n    const blob = new Blob([scriptContent], { type: 'text/javascript' });\n    return createResourceUrlInternal(URL.createObjectURL(blob));\n}\n/**\n * A function to safely retrieve the base URI from the Window object and set it\n * at the beginning of a given path-relative (starts with \"/\") resource url.\n *\n * @param pathRelativeUrl The resource to which the origin shall be prepended.\n */\nexport function toAbsoluteResourceUrl(pathRelativeUrl) {\n    const originalUrl = unwrapResourceUrl(pathRelativeUrl).toString();\n    const qualifiedUrl = new URL(originalUrl, window.document.baseURI);\n    return createResourceUrlInternal(qualifiedUrl.toString());\n}\n","/**\n * @license\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { unwrapUrlOrSanitize } from '../../builders/url_builders.js';\n/**\n * open calls {@link Window.open} on the given {@link Window}, given a\n * target {@link Url}.\n */\nexport function open(win, url, target, features) {\n    const sanitizedUrl = unwrapUrlOrSanitize(url);\n    if (sanitizedUrl !== undefined) {\n        return win.open(sanitizedUrl, target, features);\n    }\n    return null;\n}\n/** Returns CSP nonce, if set for any script tag. */\nexport function getScriptNonce(win) {\n    return getNonceFor('script', win);\n}\n/** Returns CSP nonce, if set for any style tag. */\nexport function getStyleNonce(win) {\n    return getNonceFor('style', win);\n}\nfunction getNonceFor(elementName, win) {\n    var _a;\n    const doc = win.document;\n    // document.querySelector can be undefined in non-browser environments.\n    const el = (_a = doc.querySelector) === null || _a === void 0 ? void 0 : _a.call(doc, `${elementName}[nonce]`);\n    if (el) {\n        // Try to get the nonce from the IDL property first, because browsers that\n        // implement additional nonce protection features (currently only Chrome) to\n        // prevent nonce stealing via CSS do not expose the nonce via attributes.\n        // See https://github.com/whatwg/html/issues/2369\n        return el['nonce'] || el.getAttribute('nonce') || '';\n    }\n    return '';\n}\n","/**\n * @license\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { unwrapResourceUrl, } from '../../internals/resource_url_impl.js';\nimport { unwrapScript } from '../../internals/script_impl.js';\nimport { getScriptNonce } from '../globals/window.js';\n/** Propagates CSP nonce to dynamically created scripts. */\nfunction setNonceForScriptElement(script) {\n    const win = script.ownerDocument && script.ownerDocument.defaultView;\n    const nonce = getScriptNonce(win || window);\n    if (nonce) {\n        script.setAttribute('nonce', nonce);\n    }\n}\n/** Sets textContent from the given SafeScript. */\nexport function setTextContent(script, v, options) {\n    script.textContent = unwrapScript(v);\n    if (options === null || options === void 0 ? void 0 : options.omitNonce)\n        return;\n    setNonceForScriptElement(script);\n}\n/** Sets the Src attribute using a TrustedResourceUrl */\nexport function setSrc(script, v, options) {\n    script.src = unwrapResourceUrl(v);\n    if (options === null || options === void 0 ? void 0 : options.omitNonce)\n        return;\n    setNonceForScriptElement(script);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n  AppCheckProvider,\n  AppCheckTokenInternal,\n  AppCheckTokenObserver\n} from './types';\nimport { Refresher } from './proactive-refresh';\nimport { Deferred } from '@firebase/util';\nimport { GreCAPTCHA } from './recaptcha';\nexport interface AppCheckState {\n  activated: boolean;\n  tokenObservers: AppCheckTokenObserver[];\n  provider?: AppCheckProvider;\n  token?: AppCheckTokenInternal;\n  cachedTokenPromise?: Promise<AppCheckTokenInternal | undefined>;\n  exchangeTokenPromise?: Promise<AppCheckTokenInternal>;\n  tokenRefresher?: Refresher;\n  reCAPTCHAState?: ReCAPTCHAState;\n  isTokenAutoRefreshEnabled?: boolean;\n}\n\nexport interface ReCAPTCHAState {\n  initialized: Deferred<GreCAPTCHA>;\n  widgetId?: string;\n  // True if the most recent recaptcha check succeeded.\n  succeeded?: boolean;\n}\n\nexport interface DebugState {\n  initialized: boolean;\n  enabled: boolean;\n  token?: Deferred<string>;\n}\n\nconst APP_CHECK_STATES = new Map<FirebaseApp, AppCheckState>();\nexport const DEFAULT_STATE: AppCheckState = {\n  activated: false,\n  tokenObservers: []\n};\n\nconst DEBUG_STATE: DebugState = {\n  initialized: false,\n  enabled: false\n};\n\n/**\n * Gets a reference to the state object.\n */\nexport function getStateReference(app: FirebaseApp): AppCheckState {\n  return APP_CHECK_STATES.get(app) || { ...DEFAULT_STATE };\n}\n\n/**\n * Set once on initialization. The map should hold the same reference to the\n * same object until this entry is deleted.\n */\nexport function setInitialState(\n  app: FirebaseApp,\n  state: AppCheckState\n): AppCheckState {\n  APP_CHECK_STATES.set(app, state);\n  return APP_CHECK_STATES.get(app) as AppCheckState;\n}\n\n// for testing only\nexport function clearState(): void {\n  APP_CHECK_STATES.clear();\n  DEBUG_STATE.enabled = false;\n  DEBUG_STATE.token = undefined;\n  DEBUG_STATE.initialized = false;\n}\n\nexport function getDebugState(): DebugState {\n  return DEBUG_STATE;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const BASE_ENDPOINT =\n  'https://content-firebaseappcheck.googleapis.com/v1';\n\nexport const EXCHANGE_RECAPTCHA_TOKEN_METHOD = 'exchangeRecaptchaV3Token';\nexport const EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD =\n  'exchangeRecaptchaEnterpriseToken';\nexport const EXCHANGE_DEBUG_TOKEN_METHOD = 'exchangeDebugToken';\n\nexport const TOKEN_REFRESH_TIME = {\n  /**\n   * The offset time before token natural expiration to run the refresh.\n   * This is currently 5 minutes.\n   */\n  OFFSET_DURATION: 5 * 60 * 1000,\n  /**\n   * This is the first retrial wait after an error. This is currently\n   * 30 seconds.\n   */\n  RETRIAL_MIN_WAIT: 30 * 1000,\n  /**\n   * This is the maximum retrial wait, currently 16 minutes.\n   */\n  RETRIAL_MAX_WAIT: 16 * 60 * 1000\n};\n\n/**\n * One day in millis, for certain error code backoffs.\n */\nexport const ONE_DAY = 24 * 60 * 60 * 1000;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\n/**\n * Port from auth proactiverefresh.js\n *\n */\n// TODO: move it to @firebase/util?\n// TODO: allow to config whether refresh should happen in the background\nexport class Refresher {\n  private pending: Deferred<unknown> | null = null;\n  private nextErrorWaitInterval: number;\n  constructor(\n    private readonly operation: () => Promise<unknown>,\n    private readonly retryPolicy: (error: unknown) => boolean,\n    private readonly getWaitDuration: () => number,\n    private readonly lowerBound: number,\n    private readonly upperBound: number\n  ) {\n    this.nextErrorWaitInterval = lowerBound;\n\n    if (lowerBound > upperBound) {\n      throw new Error(\n        'Proactive refresh lower bound greater than upper bound!'\n      );\n    }\n  }\n\n  start(): void {\n    this.nextErrorWaitInterval = this.lowerBound;\n    this.process(true).catch(() => {\n      /* we don't care about the result */\n    });\n  }\n\n  stop(): void {\n    if (this.pending) {\n      this.pending.reject('cancelled');\n      this.pending = null;\n    }\n  }\n\n  isRunning(): boolean {\n    return !!this.pending;\n  }\n\n  private async process(hasSucceeded: boolean): Promise<void> {\n    this.stop();\n    try {\n      this.pending = new Deferred();\n      this.pending.promise.catch(_e => {\n        /* ignore */\n      });\n      await sleep(this.getNextRun(hasSucceeded));\n\n      // Why do we resolve a promise, then immediate wait for it?\n      // We do it to make the promise chain cancellable.\n      // We can call stop() which rejects the promise before the following line execute, which makes\n      // the code jump to the catch block.\n      // TODO: unit test this\n      this.pending.resolve();\n      await this.pending.promise;\n      this.pending = new Deferred();\n      this.pending.promise.catch(_e => {\n        /* ignore */\n      });\n      await this.operation();\n\n      this.pending.resolve();\n      await this.pending.promise;\n\n      this.process(true).catch(() => {\n        /* we don't care about the result */\n      });\n    } catch (error) {\n      if (this.retryPolicy(error)) {\n        this.process(false).catch(() => {\n          /* we don't care about the result */\n        });\n      } else {\n        this.stop();\n      }\n    }\n  }\n\n  private getNextRun(hasSucceeded: boolean): number {\n    if (hasSucceeded) {\n      // If last operation succeeded, reset next error wait interval and return\n      // the default wait duration.\n      this.nextErrorWaitInterval = this.lowerBound;\n      // Return typical wait duration interval after a successful operation.\n      return this.getWaitDuration();\n    } else {\n      // Get next error wait interval.\n      const currentErrorWaitInterval = this.nextErrorWaitInterval;\n      // Double interval for next consecutive error.\n      this.nextErrorWaitInterval *= 2;\n      // Make sure next wait interval does not exceed the maximum upper bound.\n      if (this.nextErrorWaitInterval > this.upperBound) {\n        this.nextErrorWaitInterval = this.upperBound;\n      }\n      return currentErrorWaitInterval;\n    }\n  }\n}\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise<void>(resolve => {\n    setTimeout(resolve, ms);\n  });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppCheckError {\n  ALREADY_INITIALIZED = 'already-initialized',\n  USE_BEFORE_ACTIVATION = 'use-before-activation',\n  FETCH_NETWORK_ERROR = 'fetch-network-error',\n  FETCH_PARSE_ERROR = 'fetch-parse-error',\n  FETCH_STATUS_ERROR = 'fetch-status-error',\n  STORAGE_OPEN = 'storage-open',\n  STORAGE_GET = 'storage-get',\n  STORAGE_WRITE = 'storage-set',\n  RECAPTCHA_ERROR = 'recaptcha-error',\n  THROTTLED = 'throttled'\n}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\n  [AppCheckError.ALREADY_INITIALIZED]:\n    'You have already called initializeAppCheck() for FirebaseApp {$appName} with ' +\n    'different options. To avoid this error, call initializeAppCheck() with the ' +\n    'same options as when it was originally called. This will return the ' +\n    'already initialized instance.',\n  [AppCheckError.USE_BEFORE_ACTIVATION]:\n    'App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. ' +\n    'Call initializeAppCheck() before instantiating other Firebase services.',\n  [AppCheckError.FETCH_NETWORK_ERROR]:\n    'Fetch failed to connect to a network. Check Internet connection. ' +\n    'Original error: {$originalErrorMessage}.',\n  [AppCheckError.FETCH_PARSE_ERROR]:\n    'Fetch client could not parse response.' +\n    ' Original error: {$originalErrorMessage}.',\n  [AppCheckError.FETCH_STATUS_ERROR]:\n    'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',\n  [AppCheckError.STORAGE_OPEN]:\n    'Error thrown when opening storage. Original error: {$originalErrorMessage}.',\n  [AppCheckError.STORAGE_GET]:\n    'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',\n  [AppCheckError.STORAGE_WRITE]:\n    'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',\n  [AppCheckError.RECAPTCHA_ERROR]: 'ReCAPTCHA error.',\n  [AppCheckError.THROTTLED]: `Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}`\n};\n\ninterface ErrorParams {\n  [AppCheckError.ALREADY_INITIALIZED]: { appName: string };\n  [AppCheckError.USE_BEFORE_ACTIVATION]: { appName: string };\n  [AppCheckError.FETCH_NETWORK_ERROR]: { originalErrorMessage: string };\n  [AppCheckError.FETCH_PARSE_ERROR]: { originalErrorMessage: string };\n  [AppCheckError.FETCH_STATUS_ERROR]: { httpStatus: number };\n  [AppCheckError.STORAGE_OPEN]: { originalErrorMessage?: string };\n  [AppCheckError.STORAGE_GET]: { originalErrorMessage?: string };\n  [AppCheckError.STORAGE_WRITE]: { originalErrorMessage?: string };\n  [AppCheckError.THROTTLED]: { time: string; httpStatus: number };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\n  'appCheck',\n  'AppCheck',\n  ERRORS\n);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GreCAPTCHA } from './recaptcha';\nimport { getStateReference } from './state';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { FirebaseApp } from '@firebase/app';\n\nexport function getRecaptcha(\n  isEnterprise: boolean = false\n): GreCAPTCHA | undefined {\n  if (isEnterprise) {\n    return self.grecaptcha?.enterprise;\n  }\n  return self.grecaptcha;\n}\n\nexport function ensureActivated(app: FirebaseApp): void {\n  if (!getStateReference(app).activated) {\n    throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n      appName: app.name\n    });\n  }\n}\n\nexport function getDurationString(durationInMillis: number): string {\n  const totalSeconds = Math.round(durationInMillis / 1000);\n  const days = Math.floor(totalSeconds / (3600 * 24));\n  const hours = Math.floor((totalSeconds - days * 3600 * 24) / 3600);\n  const minutes = Math.floor(\n    (totalSeconds - days * 3600 * 24 - hours * 3600) / 60\n  );\n  const seconds = totalSeconds - days * 3600 * 24 - hours * 3600 - minutes * 60;\n\n  let result = '';\n  if (days) {\n    result += pad(days) + 'd:';\n  }\n  if (hours) {\n    result += pad(hours) + 'h:';\n  }\n  result += pad(minutes) + 'm:' + pad(seconds) + 's';\n  return result;\n}\n\nfunction pad(value: number): string {\n  if (value === 0) {\n    return '00';\n  }\n  return value >= 10 ? value.toString() : '0' + value;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  BASE_ENDPOINT,\n  EXCHANGE_DEBUG_TOKEN_METHOD,\n  EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD,\n  EXCHANGE_RECAPTCHA_TOKEN_METHOD\n} from './constants';\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { Provider } from '@firebase/component';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Response JSON returned from AppCheck server endpoint.\n */\ninterface AppCheckResponse {\n  token: string;\n  // timeToLive\n  ttl: string;\n}\n\ninterface AppCheckRequest {\n  url: string;\n  body: { [key: string]: string };\n}\n\nexport async function exchangeToken(\n  { url, body }: AppCheckRequest,\n  heartbeatServiceProvider: Provider<'heartbeat'>\n): Promise<AppCheckTokenInternal> {\n  const headers: HeadersInit = {\n    'Content-Type': 'application/json'\n  };\n  // If heartbeat service exists, add heartbeat header string to the header.\n  const heartbeatService = heartbeatServiceProvider.getImmediate({\n    optional: true\n  });\n  if (heartbeatService) {\n    const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n    if (heartbeatsHeader) {\n      headers['X-Firebase-Client'] = heartbeatsHeader;\n    }\n  }\n  const options: RequestInit = {\n    method: 'POST',\n    body: JSON.stringify(body),\n    headers\n  };\n  let response;\n  try {\n    response = await fetch(url, options);\n  } catch (originalError) {\n    throw ERROR_FACTORY.create(AppCheckError.FETCH_NETWORK_ERROR, {\n      originalErrorMessage: (originalError as Error)?.message\n    });\n  }\n\n  if (response.status !== 200) {\n    throw ERROR_FACTORY.create(AppCheckError.FETCH_STATUS_ERROR, {\n      httpStatus: response.status\n    });\n  }\n\n  let responseBody: AppCheckResponse;\n  try {\n    // JSON parsing throws SyntaxError if the response body isn't a JSON string.\n    responseBody = await response.json();\n  } catch (originalError) {\n    throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n      originalErrorMessage: (originalError as Error)?.message\n    });\n  }\n\n  // Protobuf duration format.\n  // https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Duration\n  const match = responseBody.ttl.match(/^([\\d.]+)(s)$/);\n  if (!match || !match[2] || isNaN(Number(match[1]))) {\n    throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n      originalErrorMessage:\n        `ttl field (timeToLive) is not in standard Protobuf Duration ` +\n        `format: ${responseBody.ttl}`\n    });\n  }\n  const timeToLiveAsNumber = Number(match[1]) * 1000;\n\n  const now = Date.now();\n  return {\n    token: responseBody.token,\n    expireTimeMillis: now + timeToLiveAsNumber,\n    issuedAtTimeMillis: now\n  };\n}\n\nexport function getExchangeRecaptchaV3TokenRequest(\n  app: FirebaseApp,\n  reCAPTCHAToken: string\n): AppCheckRequest {\n  const { projectId, appId, apiKey } = app.options;\n\n  return {\n    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_TOKEN_METHOD}?key=${apiKey}`,\n    body: {\n      'recaptcha_v3_token': reCAPTCHAToken\n    }\n  };\n}\n\nexport function getExchangeRecaptchaEnterpriseTokenRequest(\n  app: FirebaseApp,\n  reCAPTCHAToken: string\n): AppCheckRequest {\n  const { projectId, appId, apiKey } = app.options;\n\n  return {\n    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD}?key=${apiKey}`,\n    body: {\n      'recaptcha_enterprise_token': reCAPTCHAToken\n    }\n  };\n}\n\nexport function getExchangeDebugTokenRequest(\n  app: FirebaseApp,\n  debugToken: string\n): AppCheckRequest {\n  const { projectId, appId, apiKey } = app.options;\n\n  return {\n    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_DEBUG_TOKEN_METHOD}?key=${apiKey}`,\n    body: {\n      // eslint-disable-next-line\n      debug_token: debugToken\n    }\n  };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { AppCheckTokenInternal } from './types';\nconst DB_NAME = 'firebase-app-check-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-app-check-store';\nconst DEBUG_TOKEN_KEY = 'debug-token';\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\nfunction getDBPromise(): Promise<IDBDatabase> {\n  if (dbPromise) {\n    return dbPromise;\n  }\n\n  dbPromise = new Promise((resolve, reject) => {\n    try {\n      const request = indexedDB.open(DB_NAME, DB_VERSION);\n\n      request.onsuccess = event => {\n        resolve((event.target as IDBOpenDBRequest).result);\n      };\n\n      request.onerror = event => {\n        reject(\n          ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n            originalErrorMessage: (event.target as IDBRequest).error?.message\n          })\n        );\n      };\n\n      request.onupgradeneeded = event => {\n        const db = (event.target as IDBOpenDBRequest).result;\n\n        // We don't use 'break' in this switch statement, the fall-through\n        // behavior is what we want, because if there are multiple versions between\n        // the old version and the current version, we want ALL the migrations\n        // that correspond to those versions to run, not only the last one.\n        // eslint-disable-next-line default-case\n        switch (event.oldVersion) {\n          case 0:\n            db.createObjectStore(STORE_NAME, {\n              keyPath: 'compositeKey'\n            });\n        }\n      };\n    } catch (e) {\n      reject(\n        ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n          originalErrorMessage: (e as Error)?.message\n        })\n      );\n    }\n  });\n\n  return dbPromise;\n}\n\nexport function readTokenFromIndexedDB(\n  app: FirebaseApp\n): Promise<AppCheckTokenInternal | undefined> {\n  return read(computeKey(app)) as Promise<AppCheckTokenInternal | undefined>;\n}\n\nexport function writeTokenToIndexedDB(\n  app: FirebaseApp,\n  token?: AppCheckTokenInternal\n): Promise<void> {\n  return write(computeKey(app), token);\n}\n\nexport function writeDebugTokenToIndexedDB(token: string): Promise<void> {\n  return write(DEBUG_TOKEN_KEY, token);\n}\n\nexport function readDebugTokenFromIndexedDB(): Promise<string | undefined> {\n  return read(DEBUG_TOKEN_KEY) as Promise<string | undefined>;\n}\n\nasync function write(key: string, value: unknown): Promise<void> {\n  const db = await getDBPromise();\n\n  const transaction = db.transaction(STORE_NAME, 'readwrite');\n  const store = transaction.objectStore(STORE_NAME);\n  const request = store.put({\n    compositeKey: key,\n    value\n  });\n\n  return new Promise((resolve, reject) => {\n    request.onsuccess = _event => {\n      resolve();\n    };\n\n    transaction.onerror = event => {\n      reject(\n        ERROR_FACTORY.create(AppCheckError.STORAGE_WRITE, {\n          originalErrorMessage: (event.target as IDBRequest).error?.message\n        })\n      );\n    };\n  });\n}\n\nasync function read(key: string): Promise<unknown> {\n  const db = await getDBPromise();\n\n  const transaction = db.transaction(STORE_NAME, 'readonly');\n  const store = transaction.objectStore(STORE_NAME);\n  const request = store.get(key);\n\n  return new Promise((resolve, reject) => {\n    request.onsuccess = event => {\n      const result = (event.target as IDBRequest).result;\n\n      if (result) {\n        resolve(result.value);\n      } else {\n        resolve(undefined);\n      }\n    };\n\n    transaction.onerror = event => {\n      reject(\n        ERROR_FACTORY.create(AppCheckError.STORAGE_GET, {\n          originalErrorMessage: (event.target as IDBRequest).error?.message\n        })\n      );\n    };\n  });\n}\n\nfunction computeKey(app: FirebaseApp): string {\n  return `${app.options.appId}-${app.name}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app-check');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { isIndexedDBAvailable, uuidv4 } from '@firebase/util';\nimport {\n  readDebugTokenFromIndexedDB,\n  readTokenFromIndexedDB,\n  writeDebugTokenToIndexedDB,\n  writeTokenToIndexedDB\n} from './indexeddb';\nimport { logger } from './logger';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Always resolves. In case of an error reading from indexeddb, resolve with undefined\n */\nexport async function readTokenFromStorage(\n  app: FirebaseApp\n): Promise<AppCheckTokenInternal | undefined> {\n  if (isIndexedDBAvailable()) {\n    let token = undefined;\n    try {\n      token = await readTokenFromIndexedDB(app);\n    } catch (e) {\n      // swallow the error and return undefined\n      logger.warn(`Failed to read token from IndexedDB. Error: ${e}`);\n    }\n    return token;\n  }\n\n  return undefined;\n}\n\n/**\n * Always resolves. In case of an error writing to indexeddb, print a warning and resolve the promise\n */\nexport function writeTokenToStorage(\n  app: FirebaseApp,\n  token?: AppCheckTokenInternal\n): Promise<void> {\n  if (isIndexedDBAvailable()) {\n    return writeTokenToIndexedDB(app, token).catch(e => {\n      // swallow the error and resolve the promise\n      logger.warn(`Failed to write token to IndexedDB. Error: ${e}`);\n    });\n  }\n\n  return Promise.resolve();\n}\n\nexport async function readOrCreateDebugTokenFromStorage(): Promise<string> {\n  /**\n   * Theoretically race condition can happen if we read, then write in 2 separate transactions.\n   * But it won't happen here, because this function will be called exactly once.\n   */\n  let existingDebugToken: string | undefined = undefined;\n  try {\n    existingDebugToken = await readDebugTokenFromIndexedDB();\n  } catch (_e) {\n    // failed to read from indexeddb. We assume there is no existing debug token, and generate a new one.\n  }\n\n  if (!existingDebugToken) {\n    // create a new debug token\n    const newToken = uuidv4();\n    // We don't need to block on writing to indexeddb\n    // In case persistence failed, a new debug token will be generated everytime the page is refreshed.\n    // It renders the debug token useless because you have to manually register(whitelist) the new token in the firebase console again and again.\n    // If you see this error trying to use debug token, it probably means you are using a browser that doesn't support indexeddb.\n    // You should switch to a different browser that supports indexeddb\n    writeDebugTokenToIndexedDB(newToken).catch(e =>\n      logger.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)\n    );\n    return newToken;\n  } else {\n    return existingDebugToken;\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getDebugState } from './state';\nimport { readOrCreateDebugTokenFromStorage } from './storage';\nimport { Deferred, getGlobal } from '@firebase/util';\n\ndeclare global {\n  // var must be used for global scopes\n  // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#type-checking-for-globalthis\n  // eslint-disable-next-line no-var\n  var FIREBASE_APPCHECK_DEBUG_TOKEN: boolean | string | undefined;\n}\n\nexport function isDebugMode(): boolean {\n  const debugState = getDebugState();\n  return debugState.enabled;\n}\n\nexport async function getDebugToken(): Promise<string> {\n  const state = getDebugState();\n\n  if (state.enabled && state.token) {\n    return state.token.promise;\n  } else {\n    // should not happen!\n    throw Error(`\n            Can't get debug token in production mode.\n        `);\n  }\n}\n\nexport function initializeDebugMode(): void {\n  const globals = getGlobal();\n  const debugState = getDebugState();\n  // Set to true if this function has been called, whether or not\n  // it enabled debug mode.\n  debugState.initialized = true;\n\n  if (\n    typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&\n    globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true\n  ) {\n    return;\n  }\n\n  debugState.enabled = true;\n  const deferredToken = new Deferred<string>();\n  debugState.token = deferredToken;\n\n  if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN === 'string') {\n    deferredToken.resolve(globals.FIREBASE_APPCHECK_DEBUG_TOKEN);\n  } else {\n    deferredToken.resolve(readOrCreateDebugTokenFromStorage());\n  }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n  if (typeof self !== 'undefined') {\n    return self;\n  }\n  if (typeof window !== 'undefined') {\n    return window;\n  }\n  if (typeof global !== 'undefined') {\n    return global;\n  }\n  throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n  AppCheckTokenResult,\n  AppCheckTokenInternal,\n  AppCheckTokenObserver,\n  ListenerType\n} from './types';\nimport { AppCheckTokenListener } from './public-types';\nimport { getStateReference } from './state';\nimport { TOKEN_REFRESH_TIME } from './constants';\nimport { Refresher } from './proactive-refresh';\nimport { ensureActivated } from './util';\nimport { exchangeToken, getExchangeDebugTokenRequest } from './client';\nimport { writeTokenToStorage } from './storage';\nimport { getDebugToken, isDebugMode } from './debug';\nimport { base64, FirebaseError } from '@firebase/util';\nimport { logger } from './logger';\nimport { AppCheckService } from './factory';\nimport { AppCheckError } from './errors';\n\n// Initial hardcoded value agreed upon across platforms for initial launch.\n// Format left open for possible dynamic error values and other fields in the future.\nexport const defaultTokenErrorData = { error: 'UNKNOWN_ERROR' };\n\n/**\n * Stringify and base64 encode token error data.\n *\n * @param tokenError Error data, currently hardcoded.\n */\nexport function formatDummyToken(\n  tokenErrorData: Record<string, string>\n): string {\n  return base64.encodeString(\n    JSON.stringify(tokenErrorData),\n    /* webSafe= */ false\n  );\n}\n\n/**\n * This function always resolves.\n * The result will contain an error field if there is any error.\n * In case there is an error, the token field in the result will be populated with a dummy value\n */\nexport async function getToken(\n  appCheck: AppCheckService,\n  forceRefresh = false\n): Promise<AppCheckTokenResult> {\n  const app = appCheck.app;\n  ensureActivated(app);\n\n  const state = getStateReference(app);\n\n  /**\n   * First check if there is a token in memory from a previous `getToken()` call.\n   */\n  let token: AppCheckTokenInternal | undefined = state.token;\n  let error: Error | undefined = undefined;\n\n  /**\n   * If an invalid token was found in memory, clear token from\n   * memory and unset the local variable `token`.\n   */\n  if (token && !isValid(token)) {\n    state.token = undefined;\n    token = undefined;\n  }\n\n  /**\n   * If there is no valid token in memory, try to load token from indexedDB.\n   */\n  if (!token) {\n    // cachedTokenPromise contains the token found in IndexedDB or undefined if not found.\n    const cachedToken = await state.cachedTokenPromise;\n    if (cachedToken) {\n      if (isValid(cachedToken)) {\n        token = cachedToken;\n      } else {\n        // If there was an invalid token in the indexedDB cache, clear it.\n        await writeTokenToStorage(app, undefined);\n      }\n    }\n  }\n\n  // Return the cached token (from either memory or indexedDB) if it's valid\n  if (!forceRefresh && token && isValid(token)) {\n    return {\n      token: token.token\n    };\n  }\n\n  // Only set to true if this `getToken()` call is making the actual\n  // REST call to the exchange endpoint, versus waiting for an already\n  // in-flight call (see debug and regular exchange endpoint paths below)\n  let shouldCallListeners = false;\n\n  /**\n   * DEBUG MODE\n   * If debug mode is set, and there is no cached token, fetch a new App\n   * Check token using the debug token, and return it directly.\n   */\n  if (isDebugMode()) {\n    // Avoid making another call to the exchange endpoint if one is in flight.\n    if (!state.exchangeTokenPromise) {\n      state.exchangeTokenPromise = exchangeToken(\n        getExchangeDebugTokenRequest(app, await getDebugToken()),\n        appCheck.heartbeatServiceProvider\n      ).finally(() => {\n        // Clear promise when settled - either resolved or rejected.\n        state.exchangeTokenPromise = undefined;\n      });\n      shouldCallListeners = true;\n    }\n    const tokenFromDebugExchange: AppCheckTokenInternal =\n      await state.exchangeTokenPromise;\n    // Write debug token to indexedDB.\n    await writeTokenToStorage(app, tokenFromDebugExchange);\n    // Write debug token to state.\n    state.token = tokenFromDebugExchange;\n    return { token: tokenFromDebugExchange.token };\n  }\n\n  /**\n   * There are no valid tokens in memory or indexedDB and we are not in\n   * debug mode.\n   * Request a new token from the exchange endpoint.\n   */\n  try {\n    // Avoid making another call to the exchange endpoint if one is in flight.\n    if (!state.exchangeTokenPromise) {\n      // state.provider is populated in initializeAppCheck()\n      // ensureActivated() at the top of this function checks that\n      // initializeAppCheck() has been called.\n      state.exchangeTokenPromise = state.provider!.getToken().finally(() => {\n        // Clear promise when settled - either resolved or rejected.\n        state.exchangeTokenPromise = undefined;\n      });\n      shouldCallListeners = true;\n    }\n    token = await getStateReference(app).exchangeTokenPromise;\n  } catch (e) {\n    if ((e as FirebaseError).code === `appCheck/${AppCheckError.THROTTLED}`) {\n      // Warn if throttled, but do not treat it as an error.\n      logger.warn((e as FirebaseError).message);\n    } else {\n      // `getToken()` should never throw, but logging error text to console will aid debugging.\n      logger.error(e);\n    }\n    // Always save error to be added to dummy token.\n    error = e as FirebaseError;\n  }\n\n  let interopTokenResult: AppCheckTokenResult | undefined;\n  if (!token) {\n    // If token is undefined, there must be an error.\n    // Return a dummy token along with the error.\n    interopTokenResult = makeDummyTokenResult(error!);\n  } else if (error) {\n    if (isValid(token)) {\n      // It's also possible a valid token exists, but there's also an error.\n      // (Such as if the token is almost expired, tries to refresh, and\n      // the exchange request fails.)\n      // We add a special error property here so that the refresher will\n      // count this as a failed attempt and use the backoff instead of\n      // retrying repeatedly with no delay, but any 3P listeners will not\n      // be hindered in getting the still-valid token.\n      interopTokenResult = {\n        token: token.token,\n        internalError: error\n      };\n    } else {\n      // No invalid tokens should make it to this step. Memory and cached tokens\n      // are checked. Other tokens are from fresh exchanges. But just in case.\n      interopTokenResult = makeDummyTokenResult(error!);\n    }\n  } else {\n    interopTokenResult = {\n      token: token.token\n    };\n    // write the new token to the memory state as well as the persistent storage.\n    // Only do it if we got a valid new token\n    state.token = token;\n    await writeTokenToStorage(app, token);\n  }\n\n  if (shouldCallListeners) {\n    notifyTokenListeners(app, interopTokenResult);\n  }\n  return interopTokenResult;\n}\n\n/**\n * Internal API for limited use tokens. Skips all FAC state and simply calls\n * the underlying provider.\n */\nexport async function getLimitedUseToken(\n  appCheck: AppCheckService\n): Promise<AppCheckTokenResult> {\n  const app = appCheck.app;\n  ensureActivated(app);\n\n  const { provider } = getStateReference(app);\n\n  if (isDebugMode()) {\n    const debugToken = await getDebugToken();\n    const { token } = await exchangeToken(\n      getExchangeDebugTokenRequest(app, debugToken),\n      appCheck.heartbeatServiceProvider\n    );\n    return { token };\n  } else {\n    // provider is definitely valid since we ensure AppCheck was activated\n    const { token } = await provider!.getToken();\n    return { token };\n  }\n}\n\nexport function addTokenListener(\n  appCheck: AppCheckService,\n  type: ListenerType,\n  listener: AppCheckTokenListener,\n  onError?: (error: Error) => void\n): void {\n  const { app } = appCheck;\n  const state = getStateReference(app);\n  const tokenObserver: AppCheckTokenObserver = {\n    next: listener,\n    error: onError,\n    type\n  };\n  state.tokenObservers = [...state.tokenObservers, tokenObserver];\n\n  // Invoke the listener async immediately if there is a valid token\n  // in memory.\n  if (state.token && isValid(state.token)) {\n    const validToken = state.token;\n    Promise.resolve()\n      .then(() => {\n        listener({ token: validToken.token });\n        initTokenRefresher(appCheck);\n      })\n      .catch(() => {\n        /* we don't care about exceptions thrown in listeners */\n      });\n  }\n\n  /**\n   * Wait for any cached token promise to resolve before starting the token\n   * refresher. The refresher checks to see if there is an existing token\n   * in state and calls the exchange endpoint if not. We should first let the\n   * IndexedDB check have a chance to populate state if it can.\n   *\n   * Listener call isn't needed here because cachedTokenPromise will call any\n   * listeners that exist when it resolves.\n   */\n\n  // state.cachedTokenPromise is always populated in `activate()`.\n  void state.cachedTokenPromise!.then(() => initTokenRefresher(appCheck));\n}\n\nexport function removeTokenListener(\n  app: FirebaseApp,\n  listener: AppCheckTokenListener\n): void {\n  const state = getStateReference(app);\n\n  const newObservers = state.tokenObservers.filter(\n    tokenObserver => tokenObserver.next !== listener\n  );\n  if (\n    newObservers.length === 0 &&\n    state.tokenRefresher &&\n    state.tokenRefresher.isRunning()\n  ) {\n    state.tokenRefresher.stop();\n  }\n\n  state.tokenObservers = newObservers;\n}\n\n/**\n * Logic to create and start refresher as needed.\n */\nfunction initTokenRefresher(appCheck: AppCheckService): void {\n  const { app } = appCheck;\n  const state = getStateReference(app);\n  // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`\n  // is not true.\n  let refresher: Refresher | undefined = state.tokenRefresher;\n  if (!refresher) {\n    refresher = createTokenRefresher(appCheck);\n    state.tokenRefresher = refresher;\n  }\n  if (!refresher.isRunning() && state.isTokenAutoRefreshEnabled) {\n    refresher.start();\n  }\n}\n\nfunction createTokenRefresher(appCheck: AppCheckService): Refresher {\n  const { app } = appCheck;\n  return new Refresher(\n    // Keep in mind when this fails for any reason other than the ones\n    // for which we should retry, it will effectively stop the proactive refresh.\n    async () => {\n      const state = getStateReference(app);\n      // If there is no token, we will try to load it from storage and use it\n      // If there is a token, we force refresh it because we know it's going to expire soon\n      let result;\n      if (!state.token) {\n        result = await getToken(appCheck);\n      } else {\n        result = await getToken(appCheck, true);\n      }\n\n      /**\n       * getToken() always resolves. In case the result has an error field defined, it means\n       * the operation failed, and we should retry.\n       */\n      if (result.error) {\n        throw result.error;\n      }\n      /**\n       * A special `internalError` field reflects that there was an error\n       * getting a new token from the exchange endpoint, but there's still a\n       * previous token that's valid for now and this should be passed to 2P/3P\n       * requests for a token. But we want this callback (`this.operation` in\n       * `Refresher`) to throw in order to kick off the Refresher's retry\n       * backoff. (Setting `hasSucceeded` to false.)\n       */\n      if (result.internalError) {\n        throw result.internalError;\n      }\n    },\n    () => {\n      return true;\n    },\n    () => {\n      const state = getStateReference(app);\n\n      if (state.token) {\n        // issuedAtTime + (50% * total TTL) + 5 minutes\n        let nextRefreshTimeMillis =\n          state.token.issuedAtTimeMillis +\n          (state.token.expireTimeMillis - state.token.issuedAtTimeMillis) *\n            0.5 +\n          5 * 60 * 1000;\n        // Do not allow refresh time to be past (expireTime - 5 minutes)\n        const latestAllowableRefresh =\n          state.token.expireTimeMillis - 5 * 60 * 1000;\n        nextRefreshTimeMillis = Math.min(\n          nextRefreshTimeMillis,\n          latestAllowableRefresh\n        );\n        return Math.max(0, nextRefreshTimeMillis - Date.now());\n      } else {\n        return 0;\n      }\n    },\n    TOKEN_REFRESH_TIME.RETRIAL_MIN_WAIT,\n    TOKEN_REFRESH_TIME.RETRIAL_MAX_WAIT\n  );\n}\n\nexport function notifyTokenListeners(\n  app: FirebaseApp,\n  token: AppCheckTokenResult\n): void {\n  const observers = getStateReference(app).tokenObservers;\n\n  for (const observer of observers) {\n    try {\n      if (observer.type === ListenerType.EXTERNAL && token.error != null) {\n        // If this listener was added by a 3P call, send any token error to\n        // the supplied error handler. A 3P observer always has an error\n        // handler.\n        observer.error!(token.error);\n      } else {\n        // If the token has no error field, always return the token.\n        // If this is a 2P listener, return the token, whether or not it\n        // has an error field.\n        observer.next(token);\n      }\n    } catch (e) {\n      // Errors in the listener function itself are always ignored.\n    }\n  }\n}\n\nexport function isValid(token: AppCheckTokenInternal): boolean {\n  return token.expireTimeMillis - Date.now() > 0;\n}\n\nfunction makeDummyTokenResult(error: Error): AppCheckTokenResult {\n  return {\n    token: formatDummyToken(defaultTokenErrorData),\n    error\n  };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppCheck } from './public-types';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { FirebaseAppCheckInternal, ListenerType } from './types';\nimport {\n  getToken,\n  getLimitedUseToken,\n  addTokenListener,\n  removeTokenListener\n} from './internal-api';\nimport { Provider } from '@firebase/component';\nimport { getStateReference } from './state';\n\n/**\n * AppCheck Service class.\n */\nexport class AppCheckService implements AppCheck, _FirebaseService {\n  constructor(\n    public app: FirebaseApp,\n    public heartbeatServiceProvider: Provider<'heartbeat'>\n  ) {}\n  _delete(): Promise<void> {\n    const { tokenObservers } = getStateReference(this.app);\n    for (const tokenObserver of tokenObservers) {\n      removeTokenListener(this.app, tokenObserver.next);\n    }\n    return Promise.resolve();\n  }\n}\n\nexport function factory(\n  app: FirebaseApp,\n  heartbeatServiceProvider: Provider<'heartbeat'>\n): AppCheckService {\n  return new AppCheckService(app, heartbeatServiceProvider);\n}\n\nexport function internalFactory(\n  appCheck: AppCheckService\n): FirebaseAppCheckInternal {\n  return {\n    getToken: forceRefresh => getToken(appCheck, forceRefresh),\n    getLimitedUseToken: () => getLimitedUseToken(appCheck),\n    addTokenListener: listener =>\n      addTokenListener(appCheck, ListenerType.INTERNAL, listener),\n    removeTokenListener: listener => removeTokenListener(appCheck.app, listener)\n  };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { getStateReference } from './state';\nimport { Deferred } from '@firebase/util';\nimport { getRecaptcha, ensureActivated } from './util';\nimport { trustedResourceUrl } from 'safevalues';\nimport { safeScriptEl } from 'safevalues/dom';\n\n// Note that these are used for testing. If they are changed, the URLs used in loadReCAPTCHAV3Script\n// and loadReCAPTCHAEnterpriseScript must also be changed. They aren't used to create the URLs\n// since trusted resource URLs must be created using template string literals.\nexport const RECAPTCHA_URL = 'https://www.google.com/recaptcha/api.js';\nexport const RECAPTCHA_ENTERPRISE_URL =\n  'https://www.google.com/recaptcha/enterprise.js';\n\nexport function initializeV3(\n  app: FirebaseApp,\n  siteKey: string\n): Promise<GreCAPTCHA> {\n  const initialized = new Deferred<GreCAPTCHA>();\n\n  const state = getStateReference(app);\n  state.reCAPTCHAState = { initialized };\n\n  const divId = makeDiv(app);\n\n  const grecaptcha = getRecaptcha(false);\n  if (!grecaptcha) {\n    loadReCAPTCHAV3Script(() => {\n      const grecaptcha = getRecaptcha(false);\n\n      if (!grecaptcha) {\n        // it shouldn't happen.\n        throw new Error('no recaptcha');\n      }\n      queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n    });\n  } else {\n    queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n  }\n  return initialized.promise;\n}\nexport function initializeEnterprise(\n  app: FirebaseApp,\n  siteKey: string\n): Promise<GreCAPTCHA> {\n  const initialized = new Deferred<GreCAPTCHA>();\n\n  const state = getStateReference(app);\n  state.reCAPTCHAState = { initialized };\n\n  const divId = makeDiv(app);\n\n  const grecaptcha = getRecaptcha(true);\n  if (!grecaptcha) {\n    loadReCAPTCHAEnterpriseScript(() => {\n      const grecaptcha = getRecaptcha(true);\n\n      if (!grecaptcha) {\n        // it shouldn't happen.\n        throw new Error('no recaptcha');\n      }\n      queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n    });\n  } else {\n    queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n  }\n  return initialized.promise;\n}\n\n/**\n * Add listener to render the widget and resolve the promise when\n * the grecaptcha.ready() event fires.\n */\nfunction queueWidgetRender(\n  app: FirebaseApp,\n  siteKey: string,\n  grecaptcha: GreCAPTCHA,\n  container: string,\n  initialized: Deferred<GreCAPTCHA>\n): void {\n  grecaptcha.ready(() => {\n    // Invisible widgets allow us to set a different siteKey for each widget,\n    // so we use them to support multiple apps\n    renderInvisibleWidget(app, siteKey, grecaptcha, container);\n    initialized.resolve(grecaptcha);\n  });\n}\n\n/**\n * Add invisible div to page.\n */\nfunction makeDiv(app: FirebaseApp): string {\n  const divId = `fire_app_check_${app.name}`;\n  const invisibleDiv = document.createElement('div');\n  invisibleDiv.id = divId;\n  invisibleDiv.style.display = 'none';\n\n  document.body.appendChild(invisibleDiv);\n  return divId;\n}\n\nexport async function getToken(app: FirebaseApp): Promise<string> {\n  ensureActivated(app);\n\n  // ensureActivated() guarantees that reCAPTCHAState is set\n  const reCAPTCHAState = getStateReference(app).reCAPTCHAState!;\n  const recaptcha = await reCAPTCHAState.initialized.promise;\n\n  return new Promise((resolve, _reject) => {\n    // Updated after initialization is complete.\n    const reCAPTCHAState = getStateReference(app).reCAPTCHAState!;\n    recaptcha.ready(() => {\n      resolve(\n        // widgetId is guaranteed to be available if reCAPTCHAState.initialized.promise resolved.\n        recaptcha.execute(reCAPTCHAState.widgetId!, {\n          action: 'fire_app_check'\n        })\n      );\n    });\n  });\n}\n\n/**\n *\n * @param app\n * @param container - Id of a HTML element.\n */\nfunction renderInvisibleWidget(\n  app: FirebaseApp,\n  siteKey: string,\n  grecaptcha: GreCAPTCHA,\n  container: string\n): void {\n  const widgetId = grecaptcha.render(container, {\n    sitekey: siteKey,\n    size: 'invisible',\n    // Success callback - set state\n    callback: () => {\n      getStateReference(app).reCAPTCHAState!.succeeded = true;\n    },\n    // Failure callback - set state\n    'error-callback': () => {\n      getStateReference(app).reCAPTCHAState!.succeeded = false;\n    }\n  });\n\n  const state = getStateReference(app);\n\n  state.reCAPTCHAState = {\n    ...state.reCAPTCHAState!, // state.reCAPTCHAState is set in the initialize()\n    widgetId\n  };\n}\n\nfunction loadReCAPTCHAV3Script(onload: () => void): void {\n  const script = document.createElement('script');\n  safeScriptEl.setSrc(\n    script,\n    trustedResourceUrl`https://www.google.com/recaptcha/api.js`\n  );\n  script.onload = onload;\n  document.head.appendChild(script);\n}\n\nfunction loadReCAPTCHAEnterpriseScript(onload: () => void): void {\n  const script = document.createElement('script');\n  safeScriptEl.setSrc(\n    script,\n    trustedResourceUrl`https://www.google.com/recaptcha/enterprise.js`\n  );\n  script.onload = onload;\n  document.head.appendChild(script);\n}\n\ndeclare global {\n  interface Window {\n    grecaptcha: GreCAPTCHATopLevel | undefined;\n  }\n}\n\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n  enterprise: GreCAPTCHA;\n}\n\nexport interface GreCAPTCHA {\n  ready: (callback: () => void) => void;\n  execute: (siteKey: string, options: { action: string }) => Promise<string>;\n  render: (\n    container: string | HTMLElement,\n    parameters: GreCAPTCHARenderOption\n  ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n  sitekey: string;\n  size: 'invisible';\n  callback: () => void;\n  'error-callback': () => void;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _getProvider } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport {\n  FirebaseError,\n  issuedAtTime,\n  calculateBackoffMillis\n} from '@firebase/util';\nimport {\n  exchangeToken,\n  getExchangeRecaptchaEnterpriseTokenRequest,\n  getExchangeRecaptchaV3TokenRequest\n} from './client';\nimport { ONE_DAY } from './constants';\nimport { AppCheckError, ERROR_FACTORY } from './errors';\nimport { CustomProviderOptions } from './public-types';\nimport {\n  getToken as getReCAPTCHAToken,\n  initializeV3 as initializeRecaptchaV3,\n  initializeEnterprise as initializeRecaptchaEnterprise\n} from './recaptcha';\nimport { getStateReference } from './state';\nimport { AppCheckProvider, AppCheckTokenInternal, ThrottleData } from './types';\nimport { getDurationString } from './util';\n\n/**\n * App Check provider that can obtain a reCAPTCHA V3 token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaV3Provider implements AppCheckProvider {\n  private _app?: FirebaseApp;\n  private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n  /**\n   * Throttle requests on certain error codes to prevent too many retries\n   * in a short time.\n   */\n  private _throttleData: ThrottleData | null = null;\n  /**\n   * Create a ReCaptchaV3Provider instance.\n   * @param siteKey - ReCAPTCHA V3 siteKey.\n   */\n  constructor(private _siteKey: string) {}\n\n  /**\n   * Returns an App Check token.\n   * @internal\n   */\n  async getToken(): Promise<AppCheckTokenInternal> {\n    throwIfThrottled(this._throttleData);\n\n    // Top-level `getToken()` has already checked that App Check is initialized\n    // and therefore this._app and this._heartbeatServiceProvider are available.\n    const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n      _e => {\n        // reCaptcha.execute() throws null which is not very descriptive.\n        throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n      }\n    );\n    // Check if a failure state was set by the recaptcha \"error-callback\".\n    if (!getStateReference(this._app!).reCAPTCHAState?.succeeded) {\n      throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n    }\n    let result;\n    try {\n      result = await exchangeToken(\n        getExchangeRecaptchaV3TokenRequest(this._app!, attestedClaimsToken),\n        this._heartbeatServiceProvider!\n      );\n    } catch (e) {\n      if (\n        (e as FirebaseError).code?.includes(AppCheckError.FETCH_STATUS_ERROR)\n      ) {\n        this._throttleData = setBackoff(\n          Number((e as FirebaseError).customData?.httpStatus),\n          this._throttleData\n        );\n        throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n          time: getDurationString(\n            this._throttleData.allowRequestsAfter - Date.now()\n          ),\n          httpStatus: this._throttleData.httpStatus\n        });\n      } else {\n        throw e;\n      }\n    }\n    // If successful, clear throttle data.\n    this._throttleData = null;\n    return result;\n  }\n\n  /**\n   * @internal\n   */\n  initialize(app: FirebaseApp): void {\n    this._app = app;\n    this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n    initializeRecaptchaV3(app, this._siteKey).catch(() => {\n      /* we don't care about the initialization result */\n    });\n  }\n\n  /**\n   * @internal\n   */\n  isEqual(otherProvider: unknown): boolean {\n    if (otherProvider instanceof ReCaptchaV3Provider) {\n      return this._siteKey === otherProvider._siteKey;\n    } else {\n      return false;\n    }\n  }\n}\n\n/**\n * App Check provider that can obtain a reCAPTCHA Enterprise token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaEnterpriseProvider implements AppCheckProvider {\n  private _app?: FirebaseApp;\n  private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n  /**\n   * Throttle requests on certain error codes to prevent too many retries\n   * in a short time.\n   */\n  private _throttleData: ThrottleData | null = null;\n  /**\n   * Create a ReCaptchaEnterpriseProvider instance.\n   * @param siteKey - reCAPTCHA Enterprise score-based site key.\n   */\n  constructor(private _siteKey: string) {}\n\n  /**\n   * Returns an App Check token.\n   * @internal\n   */\n  async getToken(): Promise<AppCheckTokenInternal> {\n    throwIfThrottled(this._throttleData);\n    // Top-level `getToken()` has already checked that App Check is initialized\n    // and therefore this._app and this._heartbeatServiceProvider are available.\n    const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n      _e => {\n        // reCaptcha.execute() throws null which is not very descriptive.\n        throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n      }\n    );\n    // Check if a failure state was set by the recaptcha \"error-callback\".\n    if (!getStateReference(this._app!).reCAPTCHAState?.succeeded) {\n      throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n    }\n    let result;\n    try {\n      result = await exchangeToken(\n        getExchangeRecaptchaEnterpriseTokenRequest(\n          this._app!,\n          attestedClaimsToken\n        ),\n        this._heartbeatServiceProvider!\n      );\n    } catch (e) {\n      if (\n        (e as FirebaseError).code?.includes(AppCheckError.FETCH_STATUS_ERROR)\n      ) {\n        this._throttleData = setBackoff(\n          Number((e as FirebaseError).customData?.httpStatus),\n          this._throttleData\n        );\n        throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n          time: getDurationString(\n            this._throttleData.allowRequestsAfter - Date.now()\n          ),\n          httpStatus: this._throttleData.httpStatus\n        });\n      } else {\n        throw e;\n      }\n    }\n    // If successful, clear throttle data.\n    this._throttleData = null;\n    return result;\n  }\n\n  /**\n   * @internal\n   */\n  initialize(app: FirebaseApp): void {\n    this._app = app;\n    this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n    initializeRecaptchaEnterprise(app, this._siteKey).catch(() => {\n      /* we don't care about the initialization result */\n    });\n  }\n\n  /**\n   * @internal\n   */\n  isEqual(otherProvider: unknown): boolean {\n    if (otherProvider instanceof ReCaptchaEnterpriseProvider) {\n      return this._siteKey === otherProvider._siteKey;\n    } else {\n      return false;\n    }\n  }\n}\n\n/**\n * Custom provider class.\n * @public\n */\nexport class CustomProvider implements AppCheckProvider {\n  private _app?: FirebaseApp;\n\n  constructor(private _customProviderOptions: CustomProviderOptions) {}\n\n  /**\n   * @internal\n   */\n  async getToken(): Promise<AppCheckTokenInternal> {\n    // custom provider\n    const customToken = await this._customProviderOptions.getToken();\n    // Try to extract IAT from custom token, in case this token is not\n    // being newly issued. JWT timestamps are in seconds since epoch.\n    const issuedAtTimeSeconds = issuedAtTime(customToken.token);\n    // Very basic validation, use current timestamp as IAT if JWT\n    // has no `iat` field or value is out of bounds.\n    const issuedAtTimeMillis =\n      issuedAtTimeSeconds !== null &&\n      issuedAtTimeSeconds < Date.now() &&\n      issuedAtTimeSeconds > 0\n        ? issuedAtTimeSeconds * 1000\n        : Date.now();\n\n    return { ...customToken, issuedAtTimeMillis };\n  }\n\n  /**\n   * @internal\n   */\n  initialize(app: FirebaseApp): void {\n    this._app = app;\n  }\n\n  /**\n   * @internal\n   */\n  isEqual(otherProvider: unknown): boolean {\n    if (otherProvider instanceof CustomProvider) {\n      return (\n        this._customProviderOptions.getToken.toString() ===\n        otherProvider._customProviderOptions.getToken.toString()\n      );\n    } else {\n      return false;\n    }\n  }\n}\n\n/**\n * Set throttle data to block requests until after a certain time\n * depending on the failed request's status code.\n * @param httpStatus - Status code of failed request.\n * @param throttleData - `ThrottleData` object containing previous throttle\n * data state.\n * @returns Data about current throttle state and expiration time.\n */\nfunction setBackoff(\n  httpStatus: number,\n  throttleData: ThrottleData | null\n): ThrottleData {\n  /**\n   * Block retries for 1 day for the following error codes:\n   *\n   * 404: Likely malformed URL.\n   *\n   * 403:\n   * - Attestation failed\n   * - Wrong API key\n   * - Project deleted\n   */\n  if (httpStatus === 404 || httpStatus === 403) {\n    return {\n      backoffCount: 1,\n      allowRequestsAfter: Date.now() + ONE_DAY,\n      httpStatus\n    };\n  } else {\n    /**\n     * For all other error codes, the time when it is ok to retry again\n     * is based on exponential backoff.\n     */\n    const backoffCount = throttleData ? throttleData.backoffCount : 0;\n    const backoffMillis = calculateBackoffMillis(backoffCount, 1000, 2);\n    return {\n      backoffCount: backoffCount + 1,\n      allowRequestsAfter: Date.now() + backoffMillis,\n      httpStatus\n    };\n  }\n}\n\nfunction throwIfThrottled(throttleData: ThrottleData | null): void {\n  if (throttleData) {\n    if (Date.now() - throttleData.allowRequestsAfter <= 0) {\n      // If before, throw.\n      throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n        time: getDurationString(throttleData.allowRequestsAfter - Date.now()),\n        httpStatus: throttleData.httpStatus\n      });\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  AppCheck,\n  AppCheckOptions,\n  AppCheckTokenResult,\n  Unsubscribe,\n  PartialObserver\n} from './public-types';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport {\n  getStateReference,\n  getDebugState,\n  DEFAULT_STATE,\n  setInitialState\n} from './state';\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\nimport { getModularInstance, ErrorFn, NextFn } from '@firebase/util';\nimport { AppCheckService } from './factory';\nimport { AppCheckProvider, ListenerType } from './types';\nimport {\n  getToken as getTokenInternal,\n  getLimitedUseToken as getLimitedUseTokenInternal,\n  addTokenListener,\n  removeTokenListener,\n  isValid,\n  notifyTokenListeners\n} from './internal-api';\nimport { readTokenFromStorage } from './storage';\nimport { getDebugToken, initializeDebugMode, isDebugMode } from './debug';\n\ndeclare module '@firebase/component' {\n  interface NameServiceMapping {\n    'app-check': AppCheckService;\n  }\n}\n\nexport {\n  ReCaptchaV3Provider,\n  CustomProvider,\n  ReCaptchaEnterpriseProvider\n} from './providers';\n\n/**\n * Activate App Check for the given app. Can be called only once per app.\n * @param app - the {@link @firebase/app#FirebaseApp} to activate App Check for\n * @param options - App Check initialization options\n * @public\n */\nexport function initializeAppCheck(\n  app: FirebaseApp = getApp(),\n  options: AppCheckOptions\n): AppCheck {\n  app = getModularInstance(app);\n  const provider = _getProvider(app, 'app-check');\n\n  // Ensure initializeDebugMode() is only called once.\n  if (!getDebugState().initialized) {\n    initializeDebugMode();\n  }\n\n  // Log a message containing the debug token when `initializeAppCheck()`\n  // is called in debug mode.\n  if (isDebugMode()) {\n    // Do not block initialization to get the token for the message.\n    void getDebugToken().then(token =>\n      // Not using logger because I don't think we ever want this accidentally hidden.\n      console.log(\n        `App Check debug token: ${token}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`\n      )\n    );\n  }\n\n  if (provider.isInitialized()) {\n    const existingInstance = provider.getImmediate();\n    const initialOptions = provider.getOptions() as unknown as AppCheckOptions;\n    if (\n      initialOptions.isTokenAutoRefreshEnabled ===\n        options.isTokenAutoRefreshEnabled &&\n      initialOptions.provider.isEqual(options.provider)\n    ) {\n      return existingInstance;\n    } else {\n      throw ERROR_FACTORY.create(AppCheckError.ALREADY_INITIALIZED, {\n        appName: app.name\n      });\n    }\n  }\n\n  const appCheck = provider.initialize({ options });\n  _activate(app, options.provider, options.isTokenAutoRefreshEnabled);\n  // If isTokenAutoRefreshEnabled is false, do not send any requests to the\n  // exchange endpoint without an explicit call from the user either directly\n  // or through another Firebase library (storage, functions, etc.)\n  if (getStateReference(app).isTokenAutoRefreshEnabled) {\n    // Adding a listener will start the refresher and fetch a token if needed.\n    // This gets a token ready and prevents a delay when an internal library\n    // requests the token.\n    // Listener function does not need to do anything, its base functionality\n    // of calling getToken() already fetches token and writes it to memory/storage.\n    addTokenListener(appCheck, ListenerType.INTERNAL, () => {});\n  }\n\n  return appCheck;\n}\n\n/**\n * Activate App Check\n * @param app - Firebase app to activate App Check for.\n * @param provider - reCAPTCHA v3 provider or\n * custom token provider.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. If undefined, defaults to the\n * value of `app.automaticDataCollectionEnabled`, which defaults to\n * false and can be set in the app config.\n */\nfunction _activate(\n  app: FirebaseApp,\n  provider: AppCheckProvider,\n  isTokenAutoRefreshEnabled?: boolean\n): void {\n  // Create an entry in the APP_CHECK_STATES map. Further changes should\n  // directly mutate this object.\n  const state = setInitialState(app, { ...DEFAULT_STATE });\n\n  state.activated = true;\n  state.provider = provider; // Read cached token from storage if it exists and store it in memory.\n  state.cachedTokenPromise = readTokenFromStorage(app).then(cachedToken => {\n    if (cachedToken && isValid(cachedToken)) {\n      state.token = cachedToken;\n      // notify all listeners with the cached token\n      notifyTokenListeners(app, { token: cachedToken.token });\n    }\n    return cachedToken;\n  });\n\n  // Use value of global `automaticDataCollectionEnabled` (which\n  // itself defaults to false if not specified in config) if\n  // `isTokenAutoRefreshEnabled` param was not provided by user.\n  state.isTokenAutoRefreshEnabled =\n    isTokenAutoRefreshEnabled === undefined\n      ? app.automaticDataCollectionEnabled\n      : isTokenAutoRefreshEnabled;\n\n  state.provider.initialize(app);\n}\n\n/**\n * Set whether App Check will automatically refresh tokens as needed.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. This overrides any value set\n * during `initializeAppCheck()`.\n * @public\n */\nexport function setTokenAutoRefreshEnabled(\n  appCheckInstance: AppCheck,\n  isTokenAutoRefreshEnabled: boolean\n): void {\n  const app = appCheckInstance.app;\n  const state = getStateReference(app);\n  // This will exist if any product libraries have called\n  // `addTokenListener()`\n  if (state.tokenRefresher) {\n    if (isTokenAutoRefreshEnabled === true) {\n      state.tokenRefresher.start();\n    } else {\n      state.tokenRefresher.stop();\n    }\n  }\n  state.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;\n}\n/**\n * Get the current App Check token. Attaches to the most recent\n * in-flight request if one is present. Returns null if no token\n * is present and no token requests are in-flight.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param forceRefresh - If true, will always try to fetch a fresh token.\n * If false, will use a cached token if found in storage.\n * @public\n */\nexport async function getToken(\n  appCheckInstance: AppCheck,\n  forceRefresh?: boolean\n): Promise<AppCheckTokenResult> {\n  const result = await getTokenInternal(\n    appCheckInstance as AppCheckService,\n    forceRefresh\n  );\n  if (result.error) {\n    throw result.error;\n  }\n  return { token: result.token };\n}\n\n/**\n * Requests a Firebase App Check token. This method should be used\n * only if you need to authorize requests to a non-Firebase backend.\n *\n * Returns limited-use tokens that are intended for use with your\n * non-Firebase backend endpoints that are protected with\n * <a href=\"https://firebase.google.com/docs/app-check/custom-resource-backend#replay-protection\">\n * Replay Protection</a>. This method\n * does not affect the token generation behavior of the\n * #getAppCheckToken() method.\n *\n * @param appCheckInstance - The App Check service instance.\n * @returns The limited use token.\n * @public\n */\nexport function getLimitedUseToken(\n  appCheckInstance: AppCheck\n): Promise<AppCheckTokenResult> {\n  return getLimitedUseTokenInternal(appCheckInstance as AppCheckService);\n}\n\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param observer - An object with `next`, `error`, and `complete`\n * properties. `next` is called with an\n * {@link AppCheckTokenResult}\n * whenever the token changes. `error` is optional and is called if an\n * error is thrown by the listener (the `next` function). `complete`\n * is unused, as the token stream is unending.\n *\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n  appCheckInstance: AppCheck,\n  observer: PartialObserver<AppCheckTokenResult>\n): Unsubscribe;\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param onNext - When the token changes, this function is called with an\n * {@link AppCheckTokenResult}.\n * @param onError - Optional. Called if there is an error thrown by the\n * listener (the `onNext` function).\n * @param onCompletion - Currently unused, as the token stream is unending.\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n  appCheckInstance: AppCheck,\n  onNext: (tokenResult: AppCheckTokenResult) => void,\n  onError?: (error: Error) => void,\n  onCompletion?: () => void\n): Unsubscribe;\n/**\n * Wraps `addTokenListener`/`removeTokenListener` methods in an `Observer`\n * pattern for public use.\n */\nexport function onTokenChanged(\n  appCheckInstance: AppCheck,\n  onNextOrObserver:\n    | ((tokenResult: AppCheckTokenResult) => void)\n    | PartialObserver<AppCheckTokenResult>,\n  onError?: (error: Error) => void,\n  /**\n   * NOTE: Although an `onCompletion` callback can be provided, it will\n   * never be called because the token stream is never-ending.\n   * It is added only for API consistency with the observer pattern, which\n   * we follow in JS APIs.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  onCompletion?: () => void\n): Unsubscribe {\n  let nextFn: NextFn<AppCheckTokenResult> = () => {};\n  let errorFn: ErrorFn = () => {};\n  if ((onNextOrObserver as PartialObserver<AppCheckTokenResult>).next != null) {\n    nextFn = (\n      onNextOrObserver as PartialObserver<AppCheckTokenResult>\n    ).next!.bind(onNextOrObserver);\n  } else {\n    nextFn = onNextOrObserver as NextFn<AppCheckTokenResult>;\n  }\n  if (\n    (onNextOrObserver as PartialObserver<AppCheckTokenResult>).error != null\n  ) {\n    errorFn = (\n      onNextOrObserver as PartialObserver<AppCheckTokenResult>\n    ).error!.bind(onNextOrObserver);\n  } else if (onError) {\n    errorFn = onError;\n  }\n  addTokenListener(\n    appCheckInstance as AppCheckService,\n    ListenerType.EXTERNAL,\n    nextFn,\n    errorFn\n  );\n  return () => removeTokenListener(appCheckInstance.app, nextFn);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n  _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n  service: Compat<ExpService> | ExpService\n): ExpService {\n  if (service && (service as Compat<ExpService>)._delegate) {\n    return (service as Compat<ExpService>)._delegate;\n  } else {\n    return service as ExpService;\n  }\n}\n","/**\n * The Firebase App Check Web SDK.\n *\n * @remarks\n * Firebase App Check does not work in a Node.js environment using `ReCaptchaV3Provider` or\n * `ReCaptchaEnterpriseProvider`, but can be used in Node.js if you use\n * `CustomProvider` and write your own attestation method.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport {\n  Component,\n  ComponentType,\n  InstantiationMode\n} from '@firebase/component';\nimport { _AppCheckComponentName } from './public-types';\nimport { factory, internalFactory } from './factory';\nimport { _AppCheckInternalComponentName } from './types';\nimport { name, version } from '../package.json';\n\n// Used by other Firebase packages.\nexport { _AppCheckInternalComponentName };\n\nexport * from './api';\nexport * from './public-types';\n\nconst APP_CHECK_NAME: _AppCheckComponentName = 'app-check';\nconst APP_CHECK_NAME_INTERNAL: _AppCheckInternalComponentName =\n  'app-check-internal';\nfunction registerAppCheck(): void {\n  // The public interface\n  _registerComponent(\n    new Component(\n      APP_CHECK_NAME,\n      container => {\n        // getImmediate for FirebaseApp will always succeed\n        const app = container.getProvider('app').getImmediate();\n        const heartbeatServiceProvider = container.getProvider('heartbeat');\n        return factory(app, heartbeatServiceProvider);\n      },\n      ComponentType.PUBLIC\n    )\n      .setInstantiationMode(InstantiationMode.EXPLICIT)\n      /**\n       * Initialize app-check-internal after app-check is initialized to make AppCheck available to\n       * other Firebase SDKs\n       */\n      .setInstanceCreatedCallback(\n        (container, _identifier, _appcheckService) => {\n          container.getProvider(APP_CHECK_NAME_INTERNAL).initialize();\n        }\n      )\n  );\n\n  // The internal interface used by other Firebase products\n  _registerComponent(\n    new Component(\n      APP_CHECK_NAME_INTERNAL,\n      container => {\n        const appCheck = container.getProvider('app-check').getImmediate();\n        return internalFactory(appCheck);\n      },\n      ComponentType.PUBLIC\n    ).setInstantiationMode(InstantiationMode.EXPLICIT)\n  );\n\n  registerVersion(name, version);\n}\n\nregisterAppCheck();\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppCheckError {\n  USE_BEFORE_ACTIVATION = 'use-before-activation'\n}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\n  [AppCheckError.USE_BEFORE_ACTIVATION]:\n    'App Check is being used before activate() is called for FirebaseApp {$appName}. ' +\n    'Call activate() before instantiating other Firebase services.'\n};\n\ninterface ErrorParams {\n  [AppCheckError.USE_BEFORE_ACTIVATION]: { appName: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\n  'appCheck',\n  'AppCheck',\n  ERRORS\n);\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  AppCheckProvider,\n  AppCheckTokenResult,\n  FirebaseAppCheck\n} from '@firebase/app-check-types';\nimport { _FirebaseService, FirebaseApp } from '@firebase/app-compat';\nimport {\n  AppCheck as AppCheckServiceExp,\n  CustomProvider,\n  initializeAppCheck,\n  ReCaptchaV3Provider,\n  ReCaptchaEnterpriseProvider,\n  setTokenAutoRefreshEnabled as setTokenAutoRefreshEnabledExp,\n  getToken as getTokenExp,\n  onTokenChanged as onTokenChangedExp\n} from '@firebase/app-check';\nimport { PartialObserver, Unsubscribe } from '@firebase/util';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\n\nexport class AppCheckService\n  implements FirebaseAppCheck, Omit<_FirebaseService, '_delegate'>\n{\n  _delegate?: AppCheckServiceExp;\n  constructor(public app: FirebaseApp) {}\n\n  activate(\n    siteKeyOrProvider: string | AppCheckProvider,\n    isTokenAutoRefreshEnabled?: boolean\n  ): void {\n    let provider:\n      | ReCaptchaV3Provider\n      | CustomProvider\n      | ReCaptchaEnterpriseProvider;\n    if (typeof siteKeyOrProvider === 'string') {\n      provider = new ReCaptchaV3Provider(siteKeyOrProvider);\n    } else if (\n      siteKeyOrProvider instanceof ReCaptchaEnterpriseProvider ||\n      siteKeyOrProvider instanceof ReCaptchaV3Provider ||\n      siteKeyOrProvider instanceof CustomProvider\n    ) {\n      provider = siteKeyOrProvider;\n    } else {\n      provider = new CustomProvider({ getToken: siteKeyOrProvider.getToken });\n    }\n    this._delegate = initializeAppCheck(this.app, {\n      provider,\n      isTokenAutoRefreshEnabled\n    });\n  }\n\n  setTokenAutoRefreshEnabled(isTokenAutoRefreshEnabled: boolean): void {\n    if (!this._delegate) {\n      throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n        appName: this.app.name\n      });\n    }\n    setTokenAutoRefreshEnabledExp(this._delegate, isTokenAutoRefreshEnabled);\n  }\n\n  getToken(forceRefresh?: boolean): Promise<AppCheckTokenResult> {\n    if (!this._delegate) {\n      throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n        appName: this.app.name\n      });\n    }\n    return getTokenExp(this._delegate, forceRefresh);\n  }\n\n  onTokenChanged(\n    onNextOrObserver:\n      | PartialObserver<AppCheckTokenResult>\n      | ((tokenResult: AppCheckTokenResult) => void),\n    onError?: (error: Error) => void,\n    onCompletion?: () => void\n  ): Unsubscribe {\n    if (!this._delegate) {\n      throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n        appName: this.app.name\n      });\n    }\n    return onTokenChangedExp(\n      this._delegate,\n      /**\n       * Exp onTokenChanged() will handle both overloads but we need\n       * to specify one to not confuse Typescript.\n       */\n      onNextOrObserver as (tokenResult: AppCheckTokenResult) => void,\n      onError,\n      onCompletion\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, {\n  _FirebaseNamespace,\n  FirebaseApp\n} from '@firebase/app-compat';\nimport { name, version } from '../package.json';\nimport {\n  Component,\n  ComponentContainer,\n  ComponentType,\n  InstanceFactory\n} from '@firebase/component';\nimport { AppCheckService } from './service';\nimport { FirebaseAppCheck } from '@firebase/app-check-types';\nimport {\n  ReCaptchaV3Provider,\n  ReCaptchaEnterpriseProvider,\n  CustomProvider\n} from '@firebase/app-check';\n\nconst factory: InstanceFactory<'appCheck-compat'> = (\n  container: ComponentContainer\n) => {\n  // Dependencies\n  const app = container.getProvider('app-compat').getImmediate();\n\n  return new AppCheckService(app as FirebaseApp);\n};\n\nexport function registerAppCheck(): void {\n  (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n    new Component(\n      'appCheck-compat',\n      factory,\n      ComponentType.PUBLIC\n    ).setServiceProps({\n      ReCaptchaEnterpriseProvider,\n      ReCaptchaV3Provider,\n      CustomProvider\n    })\n  );\n}\n\nregisterAppCheck();\nfirebase.registerVersion(name, version);\n\n/**\n * Define extension behavior of `registerAppCheck`\n */\ndeclare module '@firebase/app-compat' {\n  interface FirebaseNamespace {\n    appCheck(app?: FirebaseApp): FirebaseAppCheck;\n  }\n  interface FirebaseApp {\n    appCheck(): FirebaseAppCheck;\n  }\n}\n"],"names":["LogLevel","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","i","length","byte1","haveByte2","byte2","haveByte3","byte3","outByte3","outByte4","push","join","encodeString","btoa","str","out","p","c","charCodeAt","stringToByteArray","decodeString","bytes","pos","c2","c3","c1","String","fromCharCode","u","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","name","base64Decode","e","console","error","Deferred","reject","resolve","promise","Promise","wrapCallback","callback","value","catch","isIndexedDBAvailable","indexedDB","FirebaseError","code","message","customData","super","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replace","PATTERN","_","key","fullMessage","jsonEval","JSON","parse","issuedAtTime","token","claims","header","signature","parts","split","decode","hasOwnProperty","uuidv4","r","Math","random","v","toString","MAX_VALUE_MILLIS","RANDOM_FACTOR","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","info","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","args","logLevel","now","Date","toISOString","method","secretToken","assertIsTemplateObject","templateObj","numExprs","raw","isTranspiled","frozenTSA","checkFrozen","TypeError","isFrozen","checkTranspiled","fn","indexOf","tag","getTrustedTypes","_a","window","trustedTypes","trustedTypesPolicy","ResourceUrlImpl","url","process","env","NODE_ENV","ensureTokenIsValid","privateDoNotAccessOrElseWrappedResourceUrl","createResourceUrlInternal","noinlineUrl","trustedScriptURL","_b","undefined","createPolicy","createHTML","s","createScript","createScriptURL","_c","getTrustedTypesPolicy","trustedResourceUrl","rest","base","toLowerCase","test","originStart","originEnd","origin","substring","hasValidOrigin","isValidPathStart","RegExp","isValidAboutUrl","encodeURIComponent","getScriptNonce","win","elementName","doc","document","el","querySelector","call","getAttribute","getNonceFor","setSrc","script","options","nonce","src","isScriptURL","unwrapResourceUrl","omitNonce","ownerDocument","defaultView","setAttribute","APP_CHECK_STATES","Map","DEFAULT_STATE","activated","tokenObservers","DEBUG_STATE","initialized","enabled","getStateReference","app","get","assign","BASE_ENDPOINT","EXCHANGE_DEBUG_TOKEN_METHOD","TOKEN_REFRESH_TIME","OFFSET_DURATION","RETRIAL_MIN_WAIT","RETRIAL_MAX_WAIT","Refresher","operation","retryPolicy","getWaitDuration","lowerBound","upperBound","pending","nextErrorWaitInterval","start","stop","isRunning","hasSucceeded","_e","ms","getNextRun","setTimeout","currentErrorWaitInterval","ERROR_FACTORY","already-initialized","use-before-activation","fetch-network-error","fetch-parse-error","fetch-status-error","storage-open","storage-get","storage-set","recaptcha-error","throttled","getRecaptcha","isEnterprise","self","grecaptcha","enterprise","ensureActivated","appName","getDurationString","durationInMillis","totalSeconds","round","days","floor","hours","minutes","seconds","result","pad","async","exchangeToken","body","heartbeatServiceProvider","headers","Content-Type","heartbeatService","getImmediate","optional","heartbeatsHeader","getHeartbeatsHeader","stringify","response","fetch","originalError","originalErrorMessage","status","httpStatus","responseBody","json","match","ttl","isNaN","Number","timeToLiveAsNumber","expireTimeMillis","issuedAtTimeMillis","getExchangeDebugTokenRequest","debugToken","projectId","appId","apiKey","debug_token","DB_NAME","DB_VERSION","STORE_NAME","DEBUG_TOKEN_KEY","dbPromise","getDBPromise","request","open","onsuccess","event","target","onerror","onupgradeneeded","db","oldVersion","createObjectStore","keyPath","write","transaction","store","objectStore","put","compositeKey","_event","read","computeKey","logger","_logLevel","_logHandler","_userLogHandler","val","setLogLevel","logHandler","userLogHandler","log","readTokenFromStorage","writeTokenToStorage","readOrCreateDebugTokenFromStorage","existingDebugToken","newToken","isDebugMode","getDebugToken","state","initializeDebugMode","globals","global","getGlobal","debugState","FIREBASE_APPCHECK_DEBUG_TOKEN","deferredToken","defaultTokenErrorData","getToken","appCheck","forceRefresh","isValid","cachedToken","cachedTokenPromise","shouldCallListeners","exchangeTokenPromise","finally","tokenFromDebugExchange","provider","interopTokenResult","internalError","makeDummyTokenResult","notifyTokenListeners","addTokenListener","listener","onError","tokenObserver","next","validToken","then","initTokenRefresher","removeTokenListener","newObservers","filter","tokenRefresher","refresher","nextRefreshTimeMillis","latestAllowableRefresh","min","max","createTokenRefresher","isTokenAutoRefreshEnabled","observer","tokenErrorData","AppCheckService","_delete","internalFactory","getLimitedUseToken","initializeV3","siteKey","reCAPTCHAState","divId","makeDiv","queueWidgetRender","onload","createElement","safeScriptEl.setSrc","head","appendChild","loadReCAPTCHAV3Script","initializeEnterprise","loadReCAPTCHAEnterpriseScript","container","ready","widgetId","render","sitekey","size","succeeded","error-callback","renderInvisibleWidget","invisibleDiv","id","style","display","recaptcha","_reject","execute","action","ReCaptchaV3Provider","_siteKey","_throttleData","throwIfThrottled","attestedClaimsToken","getReCAPTCHAToken","_app","reCAPTCHAToken","recaptcha_v3_token","getExchangeRecaptchaV3TokenRequest","_heartbeatServiceProvider","includes","setBackoff","time","allowRequestsAfter","initialize","_getProvider","initializeRecaptchaV3","isEqual","otherProvider","ReCaptchaEnterpriseProvider","recaptcha_enterprise_token","getExchangeRecaptchaEnterpriseTokenRequest","initializeRecaptchaEnterprise","CustomProvider","_customProviderOptions","customToken","issuedAtTimeSeconds","throttleData","backoffCount","currBaseValue","randomWait","backoffMillis","backoffFactor","pow","initializeAppCheck","getApp","_delegate","isInitialized","existingInstance","initialOptions","getOptions","set","setInitialState","automaticDataCollectionEnabled","_activate","APP_CHECK_NAME_INTERNAL","_registerComponent","getProvider","_identifier","_appcheckService","registerVersion","activate","siteKeyOrProvider","setTokenAutoRefreshEnabled","appCheckInstance","setTokenAutoRefreshEnabledExp","getTokenInternal","getTokenExp","onTokenChanged","onNextOrObserver","onCompletion","nextFn","errorFn","bind","onTokenChangedExp","factory","firebase","INTERNAL","registerComponent"],"mappings":"2bAsDYA,EAAAA,UCrCZ,MAyFaC,EAAiB,CAI5BC,eAAgB,KAKhBC,eAAgB,KAMhBC,sBAAuB,KAMvBC,sBAAuB,KAMvBC,kBACE,iEAKFC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