No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

firebase-auth.js.map 743KB

1
  1. {"version":3,"file":"firebase-auth.js","sources":["../../util/dist/index.esm2017.js","../../logger/dist/esm/index.esm2017.js","../../../node_modules/tslib/tslib.es6.js","../../component/dist/esm/index.esm2017.js","../../auth/dist/esm2017/index-e5b3cc81.js","../../auth/dist/esm2017/internal.js","../src/platform.ts","../src/persistence.ts","../src/popup_redirect.ts","../src/wrap.ts","../src/user_credential.ts","../src/user.ts","../src/auth.ts","../src/phone_auth_provider.ts","../src/recaptcha_verifier.ts","../index.ts"],"sourcesContent":["/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nconst CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nconst assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nconst assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst stringToByteArray$1 = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n const c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n const c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n const c4 = bytes[pos++];\r\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray(input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n const byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length; i += 3) {\r\n const byte1 = input[i];\r\n const haveByte2 = i + 1 < input.length;\r\n const byte2 = haveByte2 ? input[i + 1] : 0;\r\n const haveByte3 = i + 2 < input.length;\r\n const byte3 = haveByte3 ? input[i + 2] : 0;\r\n const outByte1 = byte1 >> 2;\r\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n let outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray(input, webSafe) {\r\n this.init_();\r\n const charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length;) {\r\n const byte1 = charToByteMap[input.charAt(i++)];\r\n const haveByte2 = i < input.length;\r\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n const haveByte3 = i < input.length;\r\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n const haveByte4 = i < input.length;\r\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw Error();\r\n }\r\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_() {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n const utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n const dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (const prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n * @public\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof global !== 'undefined') {\r\n return global;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\r\n * The dots are in parens because certain compilers (Vite?) cannot\r\n * handle seeing that variable in comments.\r\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n return;\r\n }\r\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n if (defaultsJsonString) {\r\n return JSON.parse(defaultsJsonString);\r\n }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n if (typeof document === 'undefined') {\r\n return;\r\n }\r\n let match;\r\n try {\r\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n }\r\n catch (e) {\r\n // Some environments such as Angular Universal SSR have a\r\n // `document` object but error on accessing `document.cookie`.\r\n return;\r\n }\r\n const decoded = match && base64Decode(match[1]);\r\n return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n * @public\r\n */\r\nconst getDefaults = () => {\r\n try {\r\n return (getDefaultsFromGlobal() ||\r\n getDefaultsFromEnvVariable() ||\r\n getDefaultsFromCookie());\r\n }\r\n catch (e) {\r\n /**\r\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n * to any environment case we have not accounted for. Log to\r\n * info instead of swallowing so we can find these unknown cases\r\n * and add paths for them if needed.\r\n */\r\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n return;\r\n }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n const host = getDefaultEmulatorHost(productName);\r\n if (!host) {\r\n return undefined;\r\n }\r\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n }\r\n // eslint-disable-next-line no-restricted-globals\r\n const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n if (host[0] === '[') {\r\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n return [host.substring(1, separatorIndex - 1), port];\r\n }\r\n else {\r\n return [host.substring(0, separatorIndex), port];\r\n }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n constructor() {\r\n this.reject = () => { };\r\n this.resolve = () => { };\r\n this.promise = new Promise((resolve, reject) => {\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n const header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n const project = projectId || 'demo-project';\r\n const iat = token.iat || 0;\r\n const sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n const payload = Object.assign({ \r\n // Set all required fields to decent defaults\r\n iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n const signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected or specified.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n var _a;\r\n const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\r\n if (forceEnvironment === 'node') {\r\n return true;\r\n }\r\n else if (forceEnvironment === 'browser') {\r\n return false;\r\n }\r\n try {\r\n return (Object.prototype.toString.call(global.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof self === 'object' && self.self === self;\r\n}\r\nfunction isBrowserExtension() {\r\n const runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n const ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n try {\r\n return typeof indexedDB === 'object';\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise((resolve, reject) => {\r\n try {\r\n let preExist = true;\r\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n const request = self.indexedDB.open(DB_CHECK_NAME);\r\n request.onsuccess = () => {\r\n request.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n }\r\n resolve(true);\r\n };\r\n request.onupgradeneeded = () => {\r\n preExist = false;\r\n };\r\n request.onerror = () => {\r\n var _a;\r\n reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n * // Typescript string literals for type-safe codes\r\n * type Err =\r\n * 'unknown' |\r\n * 'object-not-found'\r\n * ;\r\n *\r\n * // Closure enum for type-safe error codes\r\n * // at-enum {string}\r\n * var Err = {\r\n * UNKNOWN: 'unknown',\r\n * OBJECT_NOT_FOUND: 'object-not-found',\r\n * }\r\n *\r\n * let errors: Map<Err, string> = {\r\n * 'generic-error': \"Unknown error\",\r\n * 'file-not-found': \"Could not find file: {$file}\",\r\n * };\r\n *\r\n * // Type-safe function - must pass a valid error code as param.\r\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n * <p>Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n * <p>Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","import { ErrorFactory, deepEqual, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';\nimport { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { __rest } from 'tslib';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enum of factors that may be used for multifactor authentication.\r\n *\r\n * @public\r\n */\r\nconst FactorId = {\r\n /** Phone as second factor */\r\n PHONE: 'phone'\r\n};\r\n/**\r\n * Enumeration of supported providers.\r\n *\r\n * @public\r\n */\r\nconst ProviderId = {\r\n /** Facebook provider ID */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub provider ID */\r\n GITHUB: 'github.com',\r\n /** Google provider ID */\r\n GOOGLE: 'google.com',\r\n /** Password provider */\r\n PASSWORD: 'password',\r\n /** Phone provider */\r\n PHONE: 'phone',\r\n /** Twitter provider ID */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported sign-in methods.\r\n *\r\n * @public\r\n */\r\nconst SignInMethod = {\r\n /** Email link sign in method */\r\n EMAIL_LINK: 'emailLink',\r\n /** Email/password sign in method */\r\n EMAIL_PASSWORD: 'password',\r\n /** Facebook sign in method */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub sign in method */\r\n GITHUB: 'github.com',\r\n /** Google sign in method */\r\n GOOGLE: 'google.com',\r\n /** Phone sign in method */\r\n PHONE: 'phone',\r\n /** Twitter sign in method */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported operation types.\r\n *\r\n * @public\r\n */\r\nconst OperationType = {\r\n /** Operation involving linking an additional provider to an already signed-in user. */\r\n LINK: 'link',\r\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\r\n REAUTHENTICATE: 'reauthenticate',\r\n /** Operation involving signing in a user. */\r\n SIGN_IN: 'signIn'\r\n};\r\n/**\r\n * An enumeration of the possible email action types.\r\n *\r\n * @public\r\n */\r\nconst ActionCodeOperation = {\r\n /** The email link sign-in action. */\r\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\r\n /** The password reset action. */\r\n PASSWORD_RESET: 'PASSWORD_RESET',\r\n /** The email revocation action. */\r\n RECOVER_EMAIL: 'RECOVER_EMAIL',\r\n /** The revert second factor addition email action. */\r\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\r\n /** The revert second factor addition email action. */\r\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\r\n /** The email verification action. */\r\n VERIFY_EMAIL: 'VERIFY_EMAIL'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _debugErrorMap() {\r\n return {\r\n [\"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',\r\n [\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */]: '',\r\n [\"app-not-authorized\" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: \"This app, identified by the domain where it's hosted, is not \" +\r\n 'authorized to use Firebase Authentication with the provided API key. ' +\r\n 'Review your key configuration in the Google API console.',\r\n [\"app-not-installed\" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +\r\n 'Android package name or iOS bundle ID) provided is not installed on ' +\r\n 'this device.',\r\n [\"captcha-check-failed\" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +\r\n 'already used or the domain associated with it does not match the list ' +\r\n 'of whitelisted domains.',\r\n [\"code-expired\" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +\r\n 'again.',\r\n [\"cordova-not-ready\" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',\r\n [\"cors-unsupported\" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',\r\n [\"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',\r\n [\"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',\r\n [\"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +\r\n 'again before retrying this request.',\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.',\r\n [\"dynamic-link-not-activated\" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\r\n 'conditions.',\r\n [\"email-change-needs-verification\" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',\r\n [\"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',\r\n [\"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +\r\n 'no longer be configured to use the emulator. Try calling ' +\r\n '\"connectAuthEmulator()\" sooner.',\r\n [\"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',\r\n [\"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',\r\n [\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',\r\n [\"invalid-app-credential\" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +\r\n ' The reCAPTCHA token response is either invalid or expired.',\r\n [\"invalid-app-id\" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',\r\n [\"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */]: \"This user's credential isn't valid for this project. This can happen \" +\r\n \"if the user's token has been tampered with, or if the user isn't for \" +\r\n 'the project associated with this API key.',\r\n [\"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +\r\n 'invalid. Please resend the verification code sms and be sure to use the ' +\r\n 'verification code provided by the user.',\r\n [\"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',\r\n [\"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\r\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\r\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\r\n 'cordova-plugin-customurlscheme.',\r\n [\"invalid-custom-token\" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',\r\n [\"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',\r\n [\"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',\r\n [\"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',\r\n [\"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',\r\n [\"invalid-cert-hash\" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',\r\n [\"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */]: 'The supplied auth credential is malformed or has expired.',\r\n [\"invalid-message-payload\" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',\r\n [\"invalid-oauth-provider\" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +\r\n 'only supports OAuth providers.',\r\n [\"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +\r\n 'specified API key.',\r\n [\"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +\r\n 'project. Edit the list of authorized domains from the Firebase console.',\r\n [\"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +\r\n 'expired, or has already been used.',\r\n [\"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',\r\n [\"invalid-persistence-type\" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',\r\n [\"invalid-phone-number\" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +\r\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\r\n 'phone numbers are written in the format [+][country code][subscriber ' +\r\n 'number including area code].',\r\n [\"invalid-provider-id\" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',\r\n [\"invalid-recipient-email\" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +\r\n 'recipient email address is invalid.',\r\n [\"invalid-sender\" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',\r\n [\"invalid-tenant-id\" /* AuthErrorCode.INVALID_TENANT_ID */]: \"The Auth instance's tenant ID is invalid.\",\r\n [\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',\r\n [\"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */]: 'An Android Package Name must be provided if the Android App is required to be installed.',\r\n [\"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\r\n 'by following the instructions in the Firebase console.',\r\n [\"missing-app-credential\" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +\r\n 'assertion. A reCAPTCHA response token needs to be provided.',\r\n [\"missing-verification-code\" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',\r\n [\"missing-continue-uri\" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',\r\n [\"missing-iframe-start\" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',\r\n [\"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',\r\n [\"missing-or-invalid-nonce\" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +\r\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\r\n 'in the ID token payload.',\r\n [\"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',\r\n [\"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',\r\n [\"missing-phone-number\" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',\r\n [\"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',\r\n [\"app-deleted\" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',\r\n [\"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',\r\n [\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',\r\n [\"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +\r\n 'sign-in credentials. Sign in using a provider associated with this ' +\r\n 'email address.',\r\n [\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\r\n [\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',\r\n [\"null-user\" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +\r\n 'requires a non-null user object.',\r\n [\"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +\r\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\r\n 'Auth section.',\r\n [\"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +\r\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\r\n ' and web storage must be enabled.',\r\n [\"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\r\n [\"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',\r\n [\"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',\r\n [\"quota-exceeded\" /* AuthErrorCode.QUOTA_EXCEEDED */]: \"The project's quota for this operation has been exceeded.\",\r\n [\"redirect-cancelled-by-user\" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',\r\n [\"redirect-operation-pending\" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',\r\n [\"rejected-credential\" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',\r\n [\"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',\r\n [\"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',\r\n [\"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */]: \"The provided tenant ID does not match the Auth instance's tenant ID\",\r\n [\"timeout\" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',\r\n [\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */]: \"The user's credential is no longer valid. The user must sign in again.\",\r\n [\"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +\r\n 'Try again later.',\r\n [\"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +\r\n 'the domain in the Firebase console.',\r\n [\"unsupported-first-factor\" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */]: 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\r\n [\"unsupported-persistence-type\" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',\r\n [\"unsupported-tenant-operation\" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',\r\n [\"unverified-email\" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',\r\n [\"user-cancelled\" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',\r\n [\"user-not-found\" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +\r\n 'have been deleted.',\r\n [\"user-disabled\" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',\r\n [\"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',\r\n [\"user-signed-out\" /* AuthErrorCode.USER_SIGNED_OUT */]: '',\r\n [\"weak-password\" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',\r\n [\"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',\r\n [\"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +\r\n 'different options. To avoid this error, call initializeAuth() with the ' +\r\n 'same options as when it was originally called, or call getAuth() to return the' +\r\n ' already initialized instance.'\r\n };\r\n}\r\nfunction _prodErrorMap() {\r\n // We will include this one message in the prod error map since by the very\r\n // nature of this error, developers will never be able to see the message\r\n // using the debugErrorMap (which is installed during auth initialization).\r\n return {\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.'\r\n };\r\n}\r\n/**\r\n * A verbose error map with detailed descriptions for most error codes.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst debugErrorMap = _debugErrorMap;\r\n/**\r\n * A minimal error map with all verbose error messages stripped.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst prodErrorMap = _prodErrorMap;\r\nconst _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());\r\n/**\r\n * A map of potential `Auth` error codes, for easier comparison with errors\r\n * thrown by the SDK.\r\n *\r\n * @remarks\r\n * Note that you can't tree-shake individual keys\r\n * in the map, so by using the map you might substantially increase your\r\n * bundle size.\r\n *\r\n * @public\r\n */\r\nconst AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\r\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\r\n ARGUMENT_ERROR: 'auth/argument-error',\r\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\r\n APP_NOT_INSTALLED: 'auth/app-not-installed',\r\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\r\n CODE_EXPIRED: 'auth/code-expired',\r\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\r\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\r\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\r\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\r\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\r\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\r\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\r\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\r\n EMAIL_EXISTS: 'auth/email-already-in-use',\r\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\r\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\r\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\r\n INTERNAL_ERROR: 'auth/internal-error',\r\n INVALID_API_KEY: 'auth/invalid-api-key',\r\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\r\n INVALID_APP_ID: 'auth/invalid-app-id',\r\n INVALID_AUTH: 'auth/invalid-user-token',\r\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\r\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\r\n INVALID_CODE: 'auth/invalid-verification-code',\r\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\r\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\r\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\r\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\r\n INVALID_EMAIL: 'auth/invalid-email',\r\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\r\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\r\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\r\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\r\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\r\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\r\n INVALID_OOB_CODE: 'auth/invalid-action-code',\r\n INVALID_ORIGIN: 'auth/unauthorized-domain',\r\n INVALID_PASSWORD: 'auth/wrong-password',\r\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\r\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\r\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\r\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\r\n INVALID_SENDER: 'auth/invalid-sender',\r\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\r\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\r\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\r\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\r\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\r\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\r\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\r\n MISSING_CODE: 'auth/missing-verification-code',\r\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\r\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\r\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\r\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\r\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\r\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\r\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\r\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\r\n MODULE_DESTROYED: 'auth/app-deleted',\r\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\r\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\r\n NULL_USER: 'auth/null-user',\r\n NO_AUTH_EVENT: 'auth/no-auth-event',\r\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\r\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\r\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\r\n POPUP_BLOCKED: 'auth/popup-blocked',\r\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\r\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\r\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\r\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\r\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\r\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\r\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\r\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\r\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\r\n TIMEOUT: 'auth/timeout',\r\n TOKEN_EXPIRED: 'auth/user-token-expired',\r\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\r\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\r\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\r\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\r\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\r\n UNVERIFIED_EMAIL: 'auth/unverified-email',\r\n USER_CANCELLED: 'auth/user-cancelled',\r\n USER_DELETED: 'auth/user-not-found',\r\n USER_DISABLED: 'auth/user-disabled',\r\n USER_MISMATCH: 'auth/user-mismatch',\r\n USER_SIGNED_OUT: 'auth/user-signed-out',\r\n WEAK_PASSWORD: 'auth/weak-password',\r\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\r\n ALREADY_INITIALIZED: 'auth/already-initialized'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/auth');\r\nfunction _logError(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.ERROR) {\r\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _fail(authOrCode, ...rest) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _createError(authOrCode, ...rest) {\r\n return createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _errorWithCustomMessage(auth, code, message) {\r\n const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });\r\n const factory = new ErrorFactory('auth', 'Firebase', errorMap);\r\n return factory.create(code, {\r\n appName: auth.name\r\n });\r\n}\r\nfunction _assertInstanceOf(auth, object, instance) {\r\n const constructorInstance = instance;\r\n if (!(object instanceof constructorInstance)) {\r\n if (constructorInstance.name !== object.constructor.name) {\r\n _fail(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n throw _errorWithCustomMessage(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +\r\n `Did you pass a reference from a different Auth SDK?`);\r\n }\r\n}\r\nfunction createErrorInternal(authOrCode, ...rest) {\r\n if (typeof authOrCode !== 'string') {\r\n const code = rest[0];\r\n const fullParams = [...rest.slice(1)];\r\n if (fullParams[0]) {\r\n fullParams[0].appName = authOrCode.name;\r\n }\r\n return authOrCode._errorFactory.create(code, ...fullParams);\r\n }\r\n return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);\r\n}\r\nfunction _assert(assertion, authOrCode, ...rest) {\r\n if (!assertion) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n }\r\n}\r\n/**\r\n * Unconditionally fails, throwing an internal error with the given message.\r\n *\r\n * @param failure type of failure encountered\r\n * @throws Error\r\n */\r\nfunction debugFail(failure) {\r\n // Log the failure in addition to throw an exception, just in case the\r\n // exception is swallowed.\r\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\r\n _logError(message);\r\n // NOTE: We don't use FirebaseError here because these are internal failures\r\n // that cannot be handled by the user. (Also it would create a circular\r\n // dependency between the error and assert modules which doesn't work.)\r\n throw new Error(message);\r\n}\r\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n *\r\n * @param assertion\r\n * @param message\r\n */\r\nfunction debugAssert(assertion, message) {\r\n if (!assertion) {\r\n debugFail(message);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst instanceCache = new Map();\r\nfunction _getInstance(cls) {\r\n debugAssert(cls instanceof Function, 'Expected a class definition');\r\n let instance = instanceCache.get(cls);\r\n if (instance) {\r\n debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');\r\n return instance;\r\n }\r\n instance = new cls();\r\n instanceCache.set(cls, instance);\r\n return instance;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Initializes an {@link Auth} instance with fine-grained control over\r\n * {@link Dependencies}.\r\n *\r\n * @remarks\r\n *\r\n * This function allows more control over the {@link Auth} instance than\r\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\r\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\r\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\r\n * need control over which persistence layer is used, or to minimize bundle\r\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\r\n *\r\n * For example, if your app only uses anonymous accounts and you only want\r\n * accounts saved for the current session, initialize `Auth` with:\r\n *\r\n * ```js\r\n * const auth = initializeAuth(app, {\r\n * persistence: browserSessionPersistence,\r\n * popupRedirectResolver: undefined,\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nfunction initializeAuth(app, deps) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n const auth = provider.getImmediate();\r\n const initialOptions = provider.getOptions();\r\n if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {\r\n return auth;\r\n }\r\n else {\r\n _fail(auth, \"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */);\r\n }\r\n }\r\n const auth = provider.initialize({ options: deps });\r\n return auth;\r\n}\r\nfunction _initializeAuthInstance(auth, deps) {\r\n const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];\r\n const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);\r\n if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {\r\n auth._updateErrorMap(deps.errorMap);\r\n }\r\n // This promise is intended to float; auth initialization happens in the\r\n // background, meanwhile the auth object may be used by the app.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _getCurrentUrl() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';\r\n}\r\nfunction _isHttpOrHttps() {\r\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\r\n}\r\nfunction _getCurrentScheme() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine whether the browser is working online\r\n */\r\nfunction _isOnline() {\r\n if (typeof navigator !== 'undefined' &&\r\n navigator &&\r\n 'onLine' in navigator &&\r\n typeof navigator.onLine === 'boolean' &&\r\n // Apply only for traditional web apps and Chrome extensions.\r\n // This is especially true for Cordova apps which have unreliable\r\n // navigator.onLine behavior unless cordova-plugin-network-information is\r\n // installed which overwrites the native navigator.onLine value and\r\n // defines navigator.connection.\r\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {\r\n return navigator.onLine;\r\n }\r\n // If we can't determine the state, assume it is online.\r\n return true;\r\n}\r\nfunction _getUserLanguage() {\r\n if (typeof navigator === 'undefined') {\r\n return null;\r\n }\r\n const navigatorLanguage = navigator;\r\n return (\r\n // Most reliable, but only supported in Chrome/Firefox.\r\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\r\n // Supported in most browsers, but returns the language of the browser\r\n // UI, not the language set in browser settings.\r\n navigatorLanguage.language ||\r\n // Couldn't determine language.\r\n null);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A structure to help pick between a range of long and short delay durations\r\n * depending on the current environment. In general, the long delay is used for\r\n * mobile environments whereas short delays are used for desktop environments.\r\n */\r\nclass Delay {\r\n constructor(shortDelay, longDelay) {\r\n this.shortDelay = shortDelay;\r\n this.longDelay = longDelay;\r\n // Internal error when improperly initialized.\r\n debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');\r\n this.isMobile = isMobileCordova() || isReactNative();\r\n }\r\n get() {\r\n if (!_isOnline()) {\r\n // Pick the shorter timeout.\r\n return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);\r\n }\r\n // If running in a mobile environment, return the long delay, otherwise\r\n // return the short delay.\r\n // This could be improved in the future to dynamically change based on other\r\n // variables instead of just reading the current environment.\r\n return this.isMobile ? this.longDelay : this.shortDelay;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _emulatorUrl(config, path) {\r\n debugAssert(config.emulator, 'Emulator should always be set here');\r\n const { url } = config.emulator;\r\n if (!path) {\r\n return url;\r\n }\r\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FetchProvider {\r\n static initialize(fetchImpl, headersImpl, responseImpl) {\r\n this.fetchImpl = fetchImpl;\r\n if (headersImpl) {\r\n this.headersImpl = headersImpl;\r\n }\r\n if (responseImpl) {\r\n this.responseImpl = responseImpl;\r\n }\r\n }\r\n static fetch() {\r\n if (this.fetchImpl) {\r\n return this.fetchImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'fetch' in self) {\r\n return self.fetch;\r\n }\r\n debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static headers() {\r\n if (this.headersImpl) {\r\n return this.headersImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Headers' in self) {\r\n return self.Headers;\r\n }\r\n debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static response() {\r\n if (this.responseImpl) {\r\n return this.responseImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Response' in self) {\r\n return self.Response;\r\n }\r\n debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Map from errors returned by the server to errors to developer visible errors\r\n */\r\nconst SERVER_ERROR_MAP = {\r\n // Custom token errors.\r\n [\"CREDENTIAL_MISMATCH\" /* ServerError.CREDENTIAL_MISMATCH */]: \"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CUSTOM_TOKEN\" /* ServerError.MISSING_CUSTOM_TOKEN */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Create Auth URI errors.\r\n [\"INVALID_IDENTIFIER\" /* ServerError.INVALID_IDENTIFIER */]: \"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CONTINUE_URI\" /* ServerError.MISSING_CONTINUE_URI */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Sign in with email and password errors (some apply to sign up too).\r\n [\"INVALID_PASSWORD\" /* ServerError.INVALID_PASSWORD */]: \"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_PASSWORD\" /* ServerError.MISSING_PASSWORD */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Sign up with email and password errors.\r\n [\"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */]: \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */,\r\n [\"PASSWORD_LOGIN_DISABLED\" /* ServerError.PASSWORD_LOGIN_DISABLED */]: \"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,\r\n // Verify assertion for sign in with credential errors:\r\n [\"INVALID_IDP_RESPONSE\" /* ServerError.INVALID_IDP_RESPONSE */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n [\"INVALID_PENDING_TOKEN\" /* ServerError.INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n [\"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_REQ_TYPE\" /* ServerError.MISSING_REQ_TYPE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Send Password reset email errors:\r\n [\"EMAIL_NOT_FOUND\" /* ServerError.EMAIL_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */,\r\n [\"RESET_PASSWORD_EXCEED_LIMIT\" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"EXPIRED_OOB_CODE\" /* ServerError.EXPIRED_OOB_CODE */]: \"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */,\r\n [\"INVALID_OOB_CODE\" /* ServerError.INVALID_OOB_CODE */]: \"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_OOB_CODE\" /* ServerError.MISSING_OOB_CODE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Operations that require ID token in request:\r\n [\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: \"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,\r\n [\"INVALID_ID_TOKEN\" /* ServerError.INVALID_ID_TOKEN */]: \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */,\r\n [\"TOKEN_EXPIRED\" /* ServerError.TOKEN_EXPIRED */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n // Other errors.\r\n [\"TOO_MANY_ATTEMPTS_TRY_LATER\" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n // Phone Auth related errors.\r\n [\"INVALID_CODE\" /* ServerError.INVALID_CODE */]: \"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */,\r\n [\"INVALID_SESSION_INFO\" /* ServerError.INVALID_SESSION_INFO */]: \"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */,\r\n [\"INVALID_TEMPORARY_PROOF\" /* ServerError.INVALID_TEMPORARY_PROOF */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n [\"MISSING_SESSION_INFO\" /* ServerError.MISSING_SESSION_INFO */]: \"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */,\r\n [\"SESSION_EXPIRED\" /* ServerError.SESSION_EXPIRED */]: \"code-expired\" /* AuthErrorCode.CODE_EXPIRED */,\r\n // Other action code errors when additional settings passed.\r\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\r\n // This is OK as this error will be caught by client side validation.\r\n [\"MISSING_ANDROID_PACKAGE_NAME\" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,\r\n [\"UNAUTHORIZED_DOMAIN\" /* ServerError.UNAUTHORIZED_DOMAIN */]: \"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,\r\n // getProjectConfig errors when clientId is passed.\r\n [\"INVALID_OAUTH_CLIENT_ID\" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: \"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,\r\n // User actions (sign-up or deletion) disabled errors.\r\n [\"ADMIN_ONLY_OPERATION\" /* ServerError.ADMIN_ONLY_OPERATION */]: \"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,\r\n // Multi factor related errors.\r\n [\"INVALID_MFA_PENDING_CREDENTIAL\" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: \"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */,\r\n [\"MFA_ENROLLMENT_NOT_FOUND\" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: \"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,\r\n [\"MISSING_MFA_ENROLLMENT_ID\" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */,\r\n [\"MISSING_MFA_PENDING_CREDENTIAL\" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: \"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */,\r\n [\"SECOND_FACTOR_EXISTS\" /* ServerError.SECOND_FACTOR_EXISTS */]: \"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,\r\n [\"SECOND_FACTOR_LIMIT_EXCEEDED\" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: \"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,\r\n // Blocking functions related errors.\r\n [\"BLOCKING_FUNCTION_ERROR_RESPONSE\" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);\r\nfunction _addTidIfNecessary(auth, request) {\r\n if (auth.tenantId && !request.tenantId) {\r\n return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });\r\n }\r\n return request;\r\n}\r\nasync function _performApiRequest(auth, method, path, request, customErrorMap = {}) {\r\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\r\n let body = {};\r\n let params = {};\r\n if (request) {\r\n if (method === \"GET\" /* HttpMethod.GET */) {\r\n params = request;\r\n }\r\n else {\r\n body = {\r\n body: JSON.stringify(request)\r\n };\r\n }\r\n }\r\n const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/json';\r\n if (auth.languageCode) {\r\n headers[\"X-Firebase-Locale\" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;\r\n }\r\n return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,\r\n headers, referrerPolicy: 'no-referrer' }, body));\r\n });\r\n}\r\nasync function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {\r\n auth._canInitEmulator = false;\r\n const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);\r\n try {\r\n const networkTimeout = new NetworkTimeout(auth);\r\n const response = await Promise.race([\r\n fetchFn(),\r\n networkTimeout.promise\r\n ]);\r\n // If we've reached this point, the fetch succeeded and the networkTimeout\r\n // didn't throw; clear the network timeout delay so that Node won't hang\r\n networkTimeout.clearNetworkTimeout();\r\n const json = await response.json();\r\n if ('needConfirmation' in json) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, json);\r\n }\r\n if (response.ok && !('errorMessage' in json)) {\r\n return json;\r\n }\r\n else {\r\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\r\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\r\n if (serverErrorCode === \"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {\r\n throw _makeTaggedError(auth, \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);\r\n }\r\n else if (serverErrorCode === \"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */) {\r\n throw _makeTaggedError(auth, \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */, json);\r\n }\r\n else if (serverErrorCode === \"USER_DISABLED\" /* ServerError.USER_DISABLED */) {\r\n throw _makeTaggedError(auth, \"user-disabled\" /* AuthErrorCode.USER_DISABLED */, json);\r\n }\r\n const authError = errorMap[serverErrorCode] ||\r\n serverErrorCode\r\n .toLowerCase()\r\n .replace(/[_\\s]+/g, '-');\r\n if (serverErrorMessage) {\r\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\r\n }\r\n else {\r\n _fail(auth, authError);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n throw e;\r\n }\r\n _fail(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);\r\n }\r\n}\r\nasync function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {\r\n const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));\r\n if ('mfaPendingCredential' in serverResponse) {\r\n _fail(auth, \"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */, {\r\n _serverResponse: serverResponse\r\n });\r\n }\r\n return serverResponse;\r\n}\r\nfunction _getFinalTarget(auth, host, path, query) {\r\n const base = `${host}${path}?${query}`;\r\n if (!auth.config.emulator) {\r\n return `${auth.config.apiScheme}://${base}`;\r\n }\r\n return _emulatorUrl(auth.config, base);\r\n}\r\nclass NetworkTimeout {\r\n constructor(auth) {\r\n this.auth = auth;\r\n // Node timers and browser timers are fundamentally incompatible, but we\r\n // don't care about the value here\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timer = null;\r\n this.promise = new Promise((_, reject) => {\r\n this.timer = setTimeout(() => {\r\n return reject(_createError(this.auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, DEFAULT_API_TIMEOUT_MS.get());\r\n });\r\n }\r\n clearNetworkTimeout() {\r\n clearTimeout(this.timer);\r\n }\r\n}\r\nfunction _makeTaggedError(auth, code, response) {\r\n const errorParams = {\r\n appName: auth.name\r\n };\r\n if (response.email) {\r\n errorParams.email = response.email;\r\n }\r\n if (response.phoneNumber) {\r\n errorParams.phoneNumber = response.phoneNumber;\r\n }\r\n const error = _createError(auth, code, errorParams);\r\n // We know customData is defined on error because errorParams is defined\r\n error.customData._tokenResponse = response;\r\n return error;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteAccount(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:delete\" /* Endpoint.DELETE_ACCOUNT */, request);\r\n}\r\nasync function deleteLinkedAccounts(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function getAccountInfo(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:lookup\" /* Endpoint.GET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction utcTimestampToDateString(utcTimestamp) {\r\n if (!utcTimestamp) {\r\n return undefined;\r\n }\r\n try {\r\n // Convert to date object.\r\n const date = new Date(Number(utcTimestamp));\r\n // Test date is valid.\r\n if (!isNaN(date.getTime())) {\r\n // Convert to UTC date string.\r\n return date.toUTCString();\r\n }\r\n }\r\n catch (e) {\r\n // Do nothing. undefined will be returned.\r\n }\r\n return undefined;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nfunction getIdToken(user, forceRefresh = false) {\r\n return getModularInstance(user).getIdToken(forceRefresh);\r\n}\r\n/**\r\n * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getIdTokenResult(user, forceRefresh = false) {\r\n const userInternal = getModularInstance(user);\r\n const token = await userInternal.getIdToken(forceRefresh);\r\n const claims = _parseToken(token);\r\n _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;\r\n const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];\r\n return {\r\n claims,\r\n token,\r\n authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),\r\n issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),\r\n expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),\r\n signInProvider: signInProvider || null,\r\n signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null\r\n };\r\n}\r\nfunction secondsStringToMilliseconds(seconds) {\r\n return Number(seconds) * 1000;\r\n}\r\nfunction _parseToken(token) {\r\n const [algorithm, payload, signature] = token.split('.');\r\n if (algorithm === undefined ||\r\n payload === undefined ||\r\n signature === undefined) {\r\n _logError('JWT malformed, contained fewer than 3 sections');\r\n return null;\r\n }\r\n try {\r\n const decoded = base64Decode(payload);\r\n if (!decoded) {\r\n _logError('Failed to decode base64 JWT payload');\r\n return null;\r\n }\r\n return JSON.parse(decoded);\r\n }\r\n catch (e) {\r\n _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());\r\n return null;\r\n }\r\n}\r\n/**\r\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\r\n */\r\nfunction _tokenExpiresIn(token) {\r\n const parsedToken = _parseToken(token);\r\n _assert(parsedToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _logoutIfInvalidated(user, promise, bypassAuthState = false) {\r\n if (bypassAuthState) {\r\n return promise;\r\n }\r\n try {\r\n return await promise;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\r\n if (user.auth.currentUser === user) {\r\n await user.auth.signOut();\r\n }\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isUserInvalidated({ code }) {\r\n return (code === `auth/${\"user-disabled\" /* AuthErrorCode.USER_DISABLED */}` ||\r\n code === `auth/${\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */}`);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ProactiveRefresh {\r\n constructor(user) {\r\n this.user = user;\r\n this.isRunning = false;\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timerId = null;\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n }\r\n _start() {\r\n if (this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = true;\r\n this.schedule();\r\n }\r\n _stop() {\r\n if (!this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = false;\r\n if (this.timerId !== null) {\r\n clearTimeout(this.timerId);\r\n }\r\n }\r\n getInterval(wasError) {\r\n var _a;\r\n if (wasError) {\r\n const interval = this.errorBackoff;\r\n this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);\r\n return interval;\r\n }\r\n else {\r\n // Reset the error backoff\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;\r\n const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;\r\n return Math.max(0, interval);\r\n }\r\n }\r\n schedule(wasError = false) {\r\n if (!this.isRunning) {\r\n // Just in case...\r\n return;\r\n }\r\n const interval = this.getInterval(wasError);\r\n this.timerId = setTimeout(async () => {\r\n await this.iteration();\r\n }, interval);\r\n }\r\n async iteration() {\r\n try {\r\n await this.user.getIdToken(true);\r\n }\r\n catch (e) {\r\n // Only retry on network errors\r\n if ((e === null || e === void 0 ? void 0 : e.code) ===\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n this.schedule(/* wasError */ true);\r\n }\r\n return;\r\n }\r\n this.schedule();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserMetadata {\r\n constructor(createdAt, lastLoginAt) {\r\n this.createdAt = createdAt;\r\n this.lastLoginAt = lastLoginAt;\r\n this._initializeTime();\r\n }\r\n _initializeTime() {\r\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\r\n this.creationTime = utcTimestampToDateString(this.createdAt);\r\n }\r\n _copy(metadata) {\r\n this.createdAt = metadata.createdAt;\r\n this.lastLoginAt = metadata.lastLoginAt;\r\n this._initializeTime();\r\n }\r\n toJSON() {\r\n return {\r\n createdAt: this.createdAt,\r\n lastLoginAt: this.lastLoginAt\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reloadWithoutSaving(user) {\r\n var _a;\r\n const auth = user.auth;\r\n const idToken = await user.getIdToken();\r\n const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));\r\n _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const coreAccount = response.users[0];\r\n user._notifyReloadListener(coreAccount);\r\n const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const providerData = mergeProviderData(user.providerData, newProviderData);\r\n // Preserves the non-nonymous status of the stored user, even if no more\r\n // credentials (federated or email/password) are linked to the user. If\r\n // the user was previously anonymous, then use provider data to update.\r\n // On the other hand, if it was not anonymous before, it should never be\r\n // considered anonymous now.\r\n const oldIsAnonymous = user.isAnonymous;\r\n const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous\r\n };\r\n Object.assign(user, updates);\r\n}\r\n/**\r\n * Reloads user account data, if signed in.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function reload(user) {\r\n const userInternal = getModularInstance(user);\r\n await _reloadWithoutSaving(userInternal);\r\n // Even though the current user hasn't changed, update\r\n // current user will trigger a persistence update w/ the\r\n // new info.\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n userInternal.auth._notifyListenersIfCurrent(userInternal);\r\n}\r\nfunction mergeProviderData(original, newData) {\r\n const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));\r\n return [...deduped, ...newData];\r\n}\r\nfunction extractProviderData(providers) {\r\n return providers.map((_a) => {\r\n var { providerId } = _a, provider = __rest(_a, [\"providerId\"]);\r\n return {\r\n providerId,\r\n uid: provider.rawId || '',\r\n displayName: provider.displayName || null,\r\n email: provider.email || null,\r\n phoneNumber: provider.phoneNumber || null,\r\n photoURL: provider.photoUrl || null\r\n };\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestStsToken(auth, refreshToken) {\r\n const response = await _performFetchWithErrorHandling(auth, {}, async () => {\r\n const body = querystring({\r\n 'grant_type': 'refresh_token',\r\n 'refresh_token': refreshToken\r\n }).slice(1);\r\n const { tokenApiHost, apiKey } = auth.config;\r\n const url = _getFinalTarget(auth, tokenApiHost, \"/v1/token\" /* Endpoint.TOKEN */, `key=${apiKey}`);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';\r\n return FetchProvider.fetch()(url, {\r\n method: \"POST\" /* HttpMethod.POST */,\r\n headers,\r\n body\r\n });\r\n });\r\n // The response comes back in snake_case. Convert to camel:\r\n return {\r\n accessToken: response.access_token,\r\n expiresIn: response.expires_in,\r\n refreshToken: response.refresh_token\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\r\n * it references AuthInternal which has a circular dependency with UserInternal.\r\n *\r\n * @internal\r\n */\r\nclass StsTokenManager {\r\n constructor() {\r\n this.refreshToken = null;\r\n this.accessToken = null;\r\n this.expirationTime = null;\r\n }\r\n get isExpired() {\r\n return (!this.expirationTime ||\r\n Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);\r\n }\r\n updateFromServerResponse(response) {\r\n _assert(response.idToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.idToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.refreshToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\r\n ? Number(response.expiresIn)\r\n : _tokenExpiresIn(response.idToken);\r\n this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);\r\n }\r\n async getToken(auth, forceRefresh = false) {\r\n _assert(!this.accessToken || this.refreshToken, auth, \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */);\r\n if (!forceRefresh && this.accessToken && !this.isExpired) {\r\n return this.accessToken;\r\n }\r\n if (this.refreshToken) {\r\n await this.refresh(auth, this.refreshToken);\r\n return this.accessToken;\r\n }\r\n return null;\r\n }\r\n clearRefreshToken() {\r\n this.refreshToken = null;\r\n }\r\n async refresh(auth, oldToken) {\r\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);\r\n this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));\r\n }\r\n updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {\r\n this.refreshToken = refreshToken || null;\r\n this.accessToken = accessToken || null;\r\n this.expirationTime = Date.now() + expiresInSec * 1000;\r\n }\r\n static fromJSON(appName, object) {\r\n const { refreshToken, accessToken, expirationTime } = object;\r\n const manager = new StsTokenManager();\r\n if (refreshToken) {\r\n _assert(typeof refreshToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.refreshToken = refreshToken;\r\n }\r\n if (accessToken) {\r\n _assert(typeof accessToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.accessToken = accessToken;\r\n }\r\n if (expirationTime) {\r\n _assert(typeof expirationTime === 'number', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.expirationTime = expirationTime;\r\n }\r\n return manager;\r\n }\r\n toJSON() {\r\n return {\r\n refreshToken: this.refreshToken,\r\n accessToken: this.accessToken,\r\n expirationTime: this.expirationTime\r\n };\r\n }\r\n _assign(stsTokenManager) {\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.refreshToken = stsTokenManager.refreshToken;\r\n this.expirationTime = stsTokenManager.expirationTime;\r\n }\r\n _clone() {\r\n return Object.assign(new StsTokenManager(), this.toJSON());\r\n }\r\n _performRefresh() {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction assertStringOrUndefined(assertion, appName) {\r\n _assert(typeof assertion === 'string' || typeof assertion === 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, { appName });\r\n}\r\nclass UserImpl {\r\n constructor(_a) {\r\n var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, [\"uid\", \"auth\", \"stsTokenManager\"]);\r\n // For the user object, provider is always Firebase.\r\n this.providerId = \"firebase\" /* ProviderId.FIREBASE */;\r\n this.proactiveRefresh = new ProactiveRefresh(this);\r\n this.reloadUserInfo = null;\r\n this.reloadListener = null;\r\n this.uid = uid;\r\n this.auth = auth;\r\n this.stsTokenManager = stsTokenManager;\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.displayName = opt.displayName || null;\r\n this.email = opt.email || null;\r\n this.emailVerified = opt.emailVerified || false;\r\n this.phoneNumber = opt.phoneNumber || null;\r\n this.photoURL = opt.photoURL || null;\r\n this.isAnonymous = opt.isAnonymous || false;\r\n this.tenantId = opt.tenantId || null;\r\n this.providerData = opt.providerData ? [...opt.providerData] : [];\r\n this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);\r\n }\r\n async getIdToken(forceRefresh) {\r\n const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));\r\n _assert(accessToken, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n if (this.accessToken !== accessToken) {\r\n this.accessToken = accessToken;\r\n await this.auth._persistUserIfCurrent(this);\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n return accessToken;\r\n }\r\n getIdTokenResult(forceRefresh) {\r\n return getIdTokenResult(this, forceRefresh);\r\n }\r\n reload() {\r\n return reload(this);\r\n }\r\n _assign(user) {\r\n if (this === user) {\r\n return;\r\n }\r\n _assert(this.uid === user.uid, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.displayName = user.displayName;\r\n this.photoURL = user.photoURL;\r\n this.email = user.email;\r\n this.emailVerified = user.emailVerified;\r\n this.phoneNumber = user.phoneNumber;\r\n this.isAnonymous = user.isAnonymous;\r\n this.tenantId = user.tenantId;\r\n this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n this.metadata._copy(user.metadata);\r\n this.stsTokenManager._assign(user.stsTokenManager);\r\n }\r\n _clone(auth) {\r\n return new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));\r\n }\r\n _onReload(callback) {\r\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\r\n _assert(!this.reloadListener, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.reloadListener = callback;\r\n if (this.reloadUserInfo) {\r\n this._notifyReloadListener(this.reloadUserInfo);\r\n this.reloadUserInfo = null;\r\n }\r\n }\r\n _notifyReloadListener(userInfo) {\r\n if (this.reloadListener) {\r\n this.reloadListener(userInfo);\r\n }\r\n else {\r\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\r\n this.reloadUserInfo = userInfo;\r\n }\r\n }\r\n _startProactiveRefresh() {\r\n this.proactiveRefresh._start();\r\n }\r\n _stopProactiveRefresh() {\r\n this.proactiveRefresh._stop();\r\n }\r\n async _updateTokensIfNecessary(response, reload = false) {\r\n let tokensRefreshed = false;\r\n if (response.idToken &&\r\n response.idToken !== this.stsTokenManager.accessToken) {\r\n this.stsTokenManager.updateFromServerResponse(response);\r\n tokensRefreshed = true;\r\n }\r\n if (reload) {\r\n await _reloadWithoutSaving(this);\r\n }\r\n await this.auth._persistUserIfCurrent(this);\r\n if (tokensRefreshed) {\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n }\r\n async delete() {\r\n const idToken = await this.getIdToken();\r\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\r\n this.stsTokenManager.clearRefreshToken();\r\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\r\n // cancels pending actions...\r\n return this.auth.signOut();\r\n }\r\n toJSON() {\r\n return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(), \r\n // Redirect event ID must be maintained in case there is a pending\r\n // redirect event.\r\n _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), { \r\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\r\n apiKey: this.auth.config.apiKey, appName: this.auth.name });\r\n }\r\n get refreshToken() {\r\n return this.stsTokenManager.refreshToken || '';\r\n }\r\n static _fromJSON(auth, object) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h;\r\n const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;\r\n const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;\r\n const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;\r\n const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;\r\n const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;\r\n const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;\r\n const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;\r\n const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;\r\n const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;\r\n _assert(uid && plainObjectTokenManager, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);\r\n _assert(typeof uid === 'string', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(displayName, auth.name);\r\n assertStringOrUndefined(email, auth.name);\r\n _assert(typeof emailVerified === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof isAnonymous === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(phoneNumber, auth.name);\r\n assertStringOrUndefined(photoURL, auth.name);\r\n assertStringOrUndefined(tenantId, auth.name);\r\n assertStringOrUndefined(_redirectEventId, auth.name);\r\n assertStringOrUndefined(createdAt, auth.name);\r\n assertStringOrUndefined(lastLoginAt, auth.name);\r\n const user = new UserImpl({\r\n uid,\r\n auth,\r\n email,\r\n emailVerified,\r\n displayName,\r\n isAnonymous,\r\n photoURL,\r\n phoneNumber,\r\n tenantId,\r\n stsTokenManager,\r\n createdAt,\r\n lastLoginAt\r\n });\r\n if (providerData && Array.isArray(providerData)) {\r\n user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n }\r\n if (_redirectEventId) {\r\n user._redirectEventId = _redirectEventId;\r\n }\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromServerResponse(idTokenResponse);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: idTokenResponse.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // Updates the user info and data and resolves with a user instance.\r\n await _reloadWithoutSaving(user);\r\n return user;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass InMemoryPersistence {\r\n constructor() {\r\n this.type = \"NONE\" /* PersistenceType.NONE */;\r\n this.storage = {};\r\n }\r\n async _isAvailable() {\r\n return true;\r\n }\r\n async _set(key, value) {\r\n this.storage[key] = value;\r\n }\r\n async _get(key) {\r\n const value = this.storage[key];\r\n return value === undefined ? null : value;\r\n }\r\n async _remove(key) {\r\n delete this.storage[key];\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n}\r\nInMemoryPersistence.type = 'NONE';\r\n/**\r\n * An implementation of {@link Persistence} of type 'NONE'.\r\n *\r\n * @public\r\n */\r\nconst inMemoryPersistence = InMemoryPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _persistenceKeyName(key, apiKey, appName) {\r\n return `${\"firebase\" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;\r\n}\r\nclass PersistenceUserManager {\r\n constructor(persistence, auth, userKey) {\r\n this.persistence = persistence;\r\n this.auth = auth;\r\n this.userKey = userKey;\r\n const { config, name } = this.auth;\r\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\r\n this.fullPersistenceKey = _persistenceKeyName(\"persistence\" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);\r\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\r\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n setCurrentUser(user) {\r\n return this.persistence._set(this.fullUserKey, user.toJSON());\r\n }\r\n async getCurrentUser() {\r\n const blob = await this.persistence._get(this.fullUserKey);\r\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\r\n }\r\n removeCurrentUser() {\r\n return this.persistence._remove(this.fullUserKey);\r\n }\r\n savePersistenceForRedirect() {\r\n return this.persistence._set(this.fullPersistenceKey, this.persistence.type);\r\n }\r\n async setPersistence(newPersistence) {\r\n if (this.persistence === newPersistence) {\r\n return;\r\n }\r\n const currentUser = await this.getCurrentUser();\r\n await this.removeCurrentUser();\r\n this.persistence = newPersistence;\r\n if (currentUser) {\r\n return this.setCurrentUser(currentUser);\r\n }\r\n }\r\n delete() {\r\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n static async create(auth, persistenceHierarchy, userKey = \"authUser\" /* KeyName.AUTH_USER */) {\r\n if (!persistenceHierarchy.length) {\r\n return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);\r\n }\r\n // Eliminate any persistences that are not available\r\n const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (await persistence._isAvailable()) {\r\n return persistence;\r\n }\r\n return undefined;\r\n }))).filter(persistence => persistence);\r\n // Fall back to the first persistence listed, or in memory if none available\r\n let selectedPersistence = availablePersistences[0] ||\r\n _getInstance(inMemoryPersistence);\r\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\r\n // Pull out the existing user, setting the chosen persistence to that\r\n // persistence if the user exists.\r\n let userToMigrate = null;\r\n // Note, here we check for a user in _all_ persistences, not just the\r\n // ones deemed available. If we can migrate a user out of a broken\r\n // persistence, we will (but only if that persistence supports migration).\r\n for (const persistence of persistenceHierarchy) {\r\n try {\r\n const blob = await persistence._get(key);\r\n if (blob) {\r\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\r\n if (persistence !== selectedPersistence) {\r\n userToMigrate = user;\r\n }\r\n selectedPersistence = persistence;\r\n break;\r\n }\r\n }\r\n catch (_a) { }\r\n }\r\n // If we find the user in a persistence that does support migration, use\r\n // that migration path (of only persistences that support migration)\r\n const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);\r\n // If the persistence does _not_ allow migration, just finish off here\r\n if (!selectedPersistence._shouldAllowMigration ||\r\n !migrationHierarchy.length) {\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n selectedPersistence = migrationHierarchy[0];\r\n if (userToMigrate) {\r\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\r\n // we'll just let it bubble to surface the error.\r\n await selectedPersistence._set(key, userToMigrate.toJSON());\r\n }\r\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\r\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\r\n await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (persistence !== selectedPersistence) {\r\n try {\r\n await persistence._remove(key);\r\n }\r\n catch (_a) { }\r\n }\r\n }));\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine the browser for the purposes of reporting usage to the API\r\n */\r\nfunction _getBrowserName(userAgent) {\r\n const ua = userAgent.toLowerCase();\r\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\r\n return \"Opera\" /* BrowserName.OPERA */;\r\n }\r\n else if (_isIEMobile(ua)) {\r\n // Windows phone IEMobile browser.\r\n return \"IEMobile\" /* BrowserName.IEMOBILE */;\r\n }\r\n else if (ua.includes('msie') || ua.includes('trident/')) {\r\n return \"IE\" /* BrowserName.IE */;\r\n }\r\n else if (ua.includes('edge/')) {\r\n return \"Edge\" /* BrowserName.EDGE */;\r\n }\r\n else if (_isFirefox(ua)) {\r\n return \"Firefox\" /* BrowserName.FIREFOX */;\r\n }\r\n else if (ua.includes('silk/')) {\r\n return \"Silk\" /* BrowserName.SILK */;\r\n }\r\n else if (_isBlackBerry(ua)) {\r\n // Blackberry browser.\r\n return \"Blackberry\" /* BrowserName.BLACKBERRY */;\r\n }\r\n else if (_isWebOS(ua)) {\r\n // WebOS default browser.\r\n return \"Webos\" /* BrowserName.WEBOS */;\r\n }\r\n else if (_isSafari(ua)) {\r\n return \"Safari\" /* BrowserName.SAFARI */;\r\n }\r\n else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&\r\n !ua.includes('edge/')) {\r\n return \"Chrome\" /* BrowserName.CHROME */;\r\n }\r\n else if (_isAndroid(ua)) {\r\n // Android stock browser.\r\n return \"Android\" /* BrowserName.ANDROID */;\r\n }\r\n else {\r\n // Most modern browsers have name/version at end of user agent string.\r\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\r\n const matches = userAgent.match(re);\r\n if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {\r\n return matches[1];\r\n }\r\n }\r\n return \"Other\" /* BrowserName.OTHER */;\r\n}\r\nfunction _isFirefox(ua = getUA()) {\r\n return /firefox\\//i.test(ua);\r\n}\r\nfunction _isSafari(userAgent = getUA()) {\r\n const ua = userAgent.toLowerCase();\r\n return (ua.includes('safari/') &&\r\n !ua.includes('chrome/') &&\r\n !ua.includes('crios/') &&\r\n !ua.includes('android'));\r\n}\r\nfunction _isChromeIOS(ua = getUA()) {\r\n return /crios\\//i.test(ua);\r\n}\r\nfunction _isIEMobile(ua = getUA()) {\r\n return /iemobile/i.test(ua);\r\n}\r\nfunction _isAndroid(ua = getUA()) {\r\n return /android/i.test(ua);\r\n}\r\nfunction _isBlackBerry(ua = getUA()) {\r\n return /blackberry/i.test(ua);\r\n}\r\nfunction _isWebOS(ua = getUA()) {\r\n return /webos/i.test(ua);\r\n}\r\nfunction _isIOS(ua = getUA()) {\r\n return (/iphone|ipad|ipod/i.test(ua) ||\r\n (/macintosh/i.test(ua) && /mobile/i.test(ua)));\r\n}\r\nfunction _isIOS7Or8(ua = getUA()) {\r\n return (/(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\r\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua));\r\n}\r\nfunction _isIOSStandalone(ua = getUA()) {\r\n var _a;\r\n return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);\r\n}\r\nfunction _isIE10() {\r\n return isIE() && document.documentMode === 10;\r\n}\r\nfunction _isMobileBrowser(ua = getUA()) {\r\n // TODO: implement getBrowserName equivalent for OS.\r\n return (_isIOS(ua) ||\r\n _isAndroid(ua) ||\r\n _isWebOS(ua) ||\r\n _isBlackBerry(ua) ||\r\n /windows phone/i.test(ua) ||\r\n _isIEMobile(ua));\r\n}\r\nfunction _isIframe() {\r\n try {\r\n // Check that the current window is not the top window.\r\n // If so, return true.\r\n return !!(window && window !== window.top);\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/*\r\n * Determine the SDK version string\r\n */\r\nfunction _getClientVersion(clientPlatform, frameworks = []) {\r\n let reportedPlatform;\r\n switch (clientPlatform) {\r\n case \"Browser\" /* ClientPlatform.BROWSER */:\r\n // In a browser environment, report the browser name.\r\n reportedPlatform = _getBrowserName(getUA());\r\n break;\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n // Technically a worker runs from a browser but we need to differentiate a\r\n // worker from a browser.\r\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\r\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\r\n break;\r\n default:\r\n reportedPlatform = clientPlatform;\r\n }\r\n const reportedFrameworks = frameworks.length\r\n ? frameworks.join(',')\r\n : 'FirebaseCore-web'; /* default value if no other framework is used */\r\n return `${reportedPlatform}/${\"JsCore\" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthMiddlewareQueue {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.queue = [];\r\n }\r\n pushCallback(callback, onAbort) {\r\n // The callback could be sync or async. Wrap it into a\r\n // function that is always async.\r\n const wrappedCallback = (user) => new Promise((resolve, reject) => {\r\n try {\r\n const result = callback(user);\r\n // Either resolve with existing promise or wrap a non-promise\r\n // return value into a promise.\r\n resolve(result);\r\n }\r\n catch (e) {\r\n // Sync callback throws.\r\n reject(e);\r\n }\r\n });\r\n // Attach the onAbort if present\r\n wrappedCallback.onAbort = onAbort;\r\n this.queue.push(wrappedCallback);\r\n const index = this.queue.length - 1;\r\n return () => {\r\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\r\n // indexing of other elements.\r\n this.queue[index] = () => Promise.resolve();\r\n };\r\n }\r\n async runMiddleware(nextUser) {\r\n if (this.auth.currentUser === nextUser) {\r\n return;\r\n }\r\n // While running the middleware, build a temporary stack of onAbort\r\n // callbacks to call if one middleware callback rejects.\r\n const onAbortStack = [];\r\n try {\r\n for (const beforeStateCallback of this.queue) {\r\n await beforeStateCallback(nextUser);\r\n // Only push the onAbort if the callback succeeds\r\n if (beforeStateCallback.onAbort) {\r\n onAbortStack.push(beforeStateCallback.onAbort);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // Run all onAbort, with separate try/catch to ignore any errors and\r\n // continue\r\n onAbortStack.reverse();\r\n for (const onAbort of onAbortStack) {\r\n try {\r\n onAbort();\r\n }\r\n catch (_) {\r\n /* swallow error */\r\n }\r\n }\r\n throw this.auth._errorFactory.create(\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */, {\r\n originalMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthImpl {\r\n constructor(app, heartbeatServiceProvider, config) {\r\n this.app = app;\r\n this.heartbeatServiceProvider = heartbeatServiceProvider;\r\n this.config = config;\r\n this.currentUser = null;\r\n this.emulatorConfig = null;\r\n this.operations = Promise.resolve();\r\n this.authStateSubscription = new Subscription(this);\r\n this.idTokenSubscription = new Subscription(this);\r\n this.beforeStateQueue = new AuthMiddlewareQueue(this);\r\n this.redirectUser = null;\r\n this.isProactiveRefreshEnabled = false;\r\n // Any network calls will set this to true and prevent subsequent emulator\r\n // initialization\r\n this._canInitEmulator = true;\r\n this._isInitialized = false;\r\n this._deleted = false;\r\n this._initializationPromise = null;\r\n this._popupRedirectResolver = null;\r\n this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;\r\n // Tracks the last notified UID for state change listeners to prevent\r\n // repeated calls to the callbacks. Undefined means it's never been\r\n // called, whereas null means it's been called with a signed out user\r\n this.lastNotifiedUid = undefined;\r\n this.languageCode = null;\r\n this.tenantId = null;\r\n this.settings = { appVerificationDisabledForTesting: false };\r\n this.frameworks = [];\r\n this.name = app.name;\r\n this.clientVersion = config.sdkClientVersion;\r\n }\r\n _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {\r\n if (popupRedirectResolver) {\r\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\r\n }\r\n // Have to check for app deletion throughout initialization (after each\r\n // promise resolution)\r\n this._initializationPromise = this.queue(async () => {\r\n var _a, _b;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);\r\n if (this._deleted) {\r\n return;\r\n }\r\n // Initialize the resolver early if necessary (only applicable to web:\r\n // this will cause the iframe to load immediately in certain cases)\r\n if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {\r\n // If this fails, don't halt auth loading\r\n try {\r\n await this._popupRedirectResolver._initialize(this);\r\n }\r\n catch (e) {\r\n /* Ignore the error */\r\n }\r\n }\r\n await this.initializeCurrentUser(popupRedirectResolver);\r\n this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this._isInitialized = true;\r\n });\r\n return this._initializationPromise;\r\n }\r\n /**\r\n * If the persistence is changed in another window, the user manager will let us know\r\n */\r\n async _onStorageEvent() {\r\n if (this._deleted) {\r\n return;\r\n }\r\n const user = await this.assertedPersistence.getCurrentUser();\r\n if (!this.currentUser && !user) {\r\n // No change, do nothing (was signed out and remained signed out).\r\n return;\r\n }\r\n // If the same user is to be synchronized.\r\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\r\n // Data update, simply copy data changes.\r\n this._currentUser._assign(user);\r\n // If tokens changed from previous user tokens, this will trigger\r\n // notifyAuthListeners_.\r\n await this.currentUser.getIdToken();\r\n return;\r\n }\r\n // Update current Auth state. Either a new login or logout.\r\n // Skip blocking callbacks, they should not apply to a change in another tab.\r\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\r\n }\r\n async initializeCurrentUser(popupRedirectResolver) {\r\n var _a;\r\n // First check to see if we have a pending redirect event.\r\n const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());\r\n let futureCurrentUser = previouslyStoredUser;\r\n let needsTocheckMiddleware = false;\r\n if (popupRedirectResolver && this.config.authDomain) {\r\n await this.getOrInitRedirectPersistenceManager();\r\n const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;\r\n const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;\r\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\r\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\r\n // matches the redirect user, then we want to initially sign in with the\r\n // new user object from result.\r\n // TODO(samgho): More thoroughly test all of this\r\n if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\r\n (result === null || result === void 0 ? void 0 : result.user)) {\r\n futureCurrentUser = result.user;\r\n needsTocheckMiddleware = true;\r\n }\r\n }\r\n // If no user in persistence, there is no current user. Set to null.\r\n if (!futureCurrentUser) {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n if (!futureCurrentUser._redirectEventId) {\r\n // This isn't a redirect link operation, we can reload and bail.\r\n // First though, ensure that we check the middleware is happy.\r\n if (needsTocheckMiddleware) {\r\n try {\r\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\r\n }\r\n catch (e) {\r\n futureCurrentUser = previouslyStoredUser;\r\n // We know this is available since the bit is only set when the\r\n // resolver is available\r\n this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));\r\n }\r\n }\r\n if (futureCurrentUser) {\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n _assert(this._popupRedirectResolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n await this.getOrInitRedirectPersistenceManager();\r\n // If the redirect user's event ID matches the current user's event ID,\r\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\r\n // This is important for the reauthenticateWithRedirect() flow.\r\n if (this.redirectUser &&\r\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {\r\n return this.directlySetCurrentUser(futureCurrentUser);\r\n }\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n async tryRedirectSignIn(redirectResolver) {\r\n // The redirect user needs to be checked (and signed in if available)\r\n // during auth initialization. All of the normal sign in and link/reauth\r\n // flows call back into auth and push things onto the promise queue. We\r\n // need to await the result of the redirect sign in *inside the promise\r\n // queue*. This presents a problem: we run into deadlock. See:\r\n // ┌> [Initialization] ─────┐\r\n // ┌> [<other queue tasks>] │\r\n // └─ [getRedirectResult] <─┘\r\n // where [] are tasks on the queue and arrows denote awaits\r\n // Initialization will never complete because it's waiting on something\r\n // that's waiting for initialization to complete!\r\n //\r\n // Instead, this method calls getRedirectResult() (stored in\r\n // _completeRedirectFn) with an optional parameter that instructs all of\r\n // the underlying auth operations to skip anything that mutates auth state.\r\n let result = null;\r\n try {\r\n // We know this._popupRedirectResolver is set since redirectResolver\r\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\r\n result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);\r\n }\r\n catch (e) {\r\n // Swallow any errors here; the code can retrieve them in\r\n // getRedirectResult().\r\n await this._setRedirectUser(null);\r\n }\r\n return result;\r\n }\r\n async reloadAndSetCurrentUserOrClear(user) {\r\n try {\r\n await _reloadWithoutSaving(user);\r\n }\r\n catch (e) {\r\n if ((e === null || e === void 0 ? void 0 : e.code) !==\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n // Something's wrong with the user's token. Log them out and remove\r\n // them from storage\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n return this.directlySetCurrentUser(user);\r\n }\r\n useDeviceLanguage() {\r\n this.languageCode = _getUserLanguage();\r\n }\r\n async _delete() {\r\n this._deleted = true;\r\n }\r\n async updateCurrentUser(userExtern) {\r\n // The public updateCurrentUser method needs to make a copy of the user,\r\n // and also check that the project matches\r\n const user = userExtern\r\n ? getModularInstance(userExtern)\r\n : null;\r\n if (user) {\r\n _assert(user.auth.config.apiKey === this.config.apiKey, this, \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */);\r\n }\r\n return this._updateCurrentUser(user && user._clone(this));\r\n }\r\n async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {\r\n if (this._deleted) {\r\n return;\r\n }\r\n if (user) {\r\n _assert(this.tenantId === user.tenantId, this, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n }\r\n if (!skipBeforeStateCallbacks) {\r\n await this.beforeStateQueue.runMiddleware(user);\r\n }\r\n return this.queue(async () => {\r\n await this.directlySetCurrentUser(user);\r\n this.notifyAuthListeners();\r\n });\r\n }\r\n async signOut() {\r\n // Run first, to block _setRedirectUser() if any callbacks fail.\r\n await this.beforeStateQueue.runMiddleware(null);\r\n // Clear the redirect user when signOut is called\r\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\r\n await this._setRedirectUser(null);\r\n }\r\n // Prevent callbacks from being called again in _updateCurrentUser, as\r\n // they were already called in the first line.\r\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\r\n }\r\n setPersistence(persistence) {\r\n return this.queue(async () => {\r\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\r\n });\r\n }\r\n _getPersistence() {\r\n return this.assertedPersistence.persistence.type;\r\n }\r\n _updateErrorMap(errorMap) {\r\n this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());\r\n }\r\n onAuthStateChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);\r\n }\r\n beforeAuthStateChanged(callback, onAbort) {\r\n return this.beforeStateQueue.pushCallback(callback, onAbort);\r\n }\r\n onIdTokenChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);\r\n }\r\n toJSON() {\r\n var _a;\r\n return {\r\n apiKey: this.config.apiKey,\r\n authDomain: this.config.authDomain,\r\n appName: this.name,\r\n currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()\r\n };\r\n }\r\n async _setRedirectUser(user, popupRedirectResolver) {\r\n const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);\r\n return user === null\r\n ? redirectManager.removeCurrentUser()\r\n : redirectManager.setCurrentUser(user);\r\n }\r\n async getOrInitRedirectPersistenceManager(popupRedirectResolver) {\r\n if (!this.redirectPersistenceManager) {\r\n const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\r\n this._popupRedirectResolver;\r\n _assert(resolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], \"redirectUser\" /* KeyName.REDIRECT_USER */);\r\n this.redirectUser =\r\n await this.redirectPersistenceManager.getCurrentUser();\r\n }\r\n return this.redirectPersistenceManager;\r\n }\r\n async _redirectUserForId(id) {\r\n var _a, _b;\r\n // Make sure we've cleared any pending persistence actions if we're not in\r\n // the initializer\r\n if (this._isInitialized) {\r\n await this.queue(async () => { });\r\n }\r\n if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {\r\n return this._currentUser;\r\n }\r\n if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {\r\n return this.redirectUser;\r\n }\r\n return null;\r\n }\r\n async _persistUserIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n return this.queue(async () => this.directlySetCurrentUser(user));\r\n }\r\n }\r\n /** Notifies listeners only if the user is current */\r\n _notifyListenersIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n this.notifyAuthListeners();\r\n }\r\n }\r\n _key() {\r\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\r\n }\r\n _startProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = true;\r\n if (this.currentUser) {\r\n this._currentUser._startProactiveRefresh();\r\n }\r\n }\r\n _stopProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = false;\r\n if (this.currentUser) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n }\r\n /** Returns the current user cast as the internal type */\r\n get _currentUser() {\r\n return this.currentUser;\r\n }\r\n notifyAuthListeners() {\r\n var _a, _b;\r\n if (!this._isInitialized) {\r\n return;\r\n }\r\n this.idTokenSubscription.next(this.currentUser);\r\n const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;\r\n if (this.lastNotifiedUid !== currentUid) {\r\n this.lastNotifiedUid = currentUid;\r\n this.authStateSubscription.next(this.currentUser);\r\n }\r\n }\r\n registerStateListener(subscription, nextOrObserver, error, completed) {\r\n if (this._deleted) {\r\n return () => { };\r\n }\r\n const cb = typeof nextOrObserver === 'function'\r\n ? nextOrObserver\r\n : nextOrObserver.next.bind(nextOrObserver);\r\n const promise = this._isInitialized\r\n ? Promise.resolve()\r\n : this._initializationPromise;\r\n _assert(promise, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // The callback needs to be called asynchronously per the spec.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n promise.then(() => cb(this.currentUser));\r\n if (typeof nextOrObserver === 'function') {\r\n return subscription.addObserver(nextOrObserver, error, completed);\r\n }\r\n else {\r\n return subscription.addObserver(nextOrObserver);\r\n }\r\n }\r\n /**\r\n * Unprotected (from race conditions) method to set the current user. This\r\n * should only be called from within a queued callback. This is necessary\r\n * because the queue shouldn't rely on another queued callback.\r\n */\r\n async directlySetCurrentUser(user) {\r\n if (this.currentUser && this.currentUser !== user) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n if (user && this.isProactiveRefreshEnabled) {\r\n user._startProactiveRefresh();\r\n }\r\n this.currentUser = user;\r\n if (user) {\r\n await this.assertedPersistence.setCurrentUser(user);\r\n }\r\n else {\r\n await this.assertedPersistence.removeCurrentUser();\r\n }\r\n }\r\n queue(action) {\r\n // In case something errors, the callback still should be called in order\r\n // to keep the promise chain alive\r\n this.operations = this.operations.then(action, action);\r\n return this.operations;\r\n }\r\n get assertedPersistence() {\r\n _assert(this.persistenceManager, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.persistenceManager;\r\n }\r\n _logFramework(framework) {\r\n if (!framework || this.frameworks.includes(framework)) {\r\n return;\r\n }\r\n this.frameworks.push(framework);\r\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\r\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\r\n this.frameworks.sort();\r\n this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());\r\n }\r\n _getFrameworks() {\r\n return this.frameworks;\r\n }\r\n async _getAdditionalHeaders() {\r\n var _a;\r\n // Additional headers on every request\r\n const headers = {\r\n [\"X-Client-Version\" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion\r\n };\r\n if (this.app.options.appId) {\r\n headers[\"X-Firebase-gmpid\" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;\r\n }\r\n // If the heartbeat service exists, add the heartbeat string\r\n const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider\r\n .getImmediate({\r\n optional: true\r\n })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());\r\n if (heartbeatsHeader) {\r\n headers[\"X-Firebase-Client\" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;\r\n }\r\n return headers;\r\n }\r\n}\r\n/**\r\n * Method to be used to cast down to our private implmentation of Auth.\r\n * It will also handle unwrapping from the compat type if necessary\r\n *\r\n * @param auth Auth object passed in from developer\r\n */\r\nfunction _castAuth(auth) {\r\n return getModularInstance(auth);\r\n}\r\n/** Helper class to wrap subscriber logic */\r\nclass Subscription {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.observer = null;\r\n this.addObserver = createSubscribe(observer => (this.observer = observer));\r\n }\r\n get next() {\r\n _assert(this.observer, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.observer.next.bind(this.observer);\r\n }\r\n}\n\n/**\r\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\r\n * Firebase Auth services.\r\n *\r\n * @remarks\r\n * This must be called synchronously immediately following the first call to\r\n * {@link initializeAuth}. Do not use with production credentials as emulator\r\n * traffic is not encrypted.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\r\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\r\n * `true` to disable the warning banner attached to the DOM.\r\n *\r\n * @public\r\n */\r\nfunction connectAuthEmulator(auth, url, options) {\r\n const authInternal = _castAuth(auth);\r\n _assert(authInternal._canInitEmulator, authInternal, \"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);\r\n _assert(/^https?:\\/\\//.test(url), authInternal, \"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);\r\n const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);\r\n const protocol = extractProtocol(url);\r\n const { host, port } = extractHostAndPort(url);\r\n const portStr = port === null ? '' : `:${port}`;\r\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\r\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\r\n authInternal.settings.appVerificationDisabledForTesting = true;\r\n authInternal.emulatorConfig = Object.freeze({\r\n host,\r\n port,\r\n protocol: protocol.replace(':', ''),\r\n options: Object.freeze({ disableWarnings })\r\n });\r\n if (!disableWarnings) {\r\n emitEmulatorWarning();\r\n }\r\n}\r\nfunction extractProtocol(url) {\r\n const protocolEnd = url.indexOf(':');\r\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\r\n}\r\nfunction extractHostAndPort(url) {\r\n const protocol = extractProtocol(url);\r\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\r\n if (!authority) {\r\n return { host: '', port: null };\r\n }\r\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\r\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\r\n if (bracketedIPv6) {\r\n const host = bracketedIPv6[1];\r\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\r\n }\r\n else {\r\n const [host, port] = hostAndPort.split(':');\r\n return { host, port: parsePort(port) };\r\n }\r\n}\r\nfunction parsePort(portStr) {\r\n if (!portStr) {\r\n return null;\r\n }\r\n const port = Number(portStr);\r\n if (isNaN(port)) {\r\n return null;\r\n }\r\n return port;\r\n}\r\nfunction emitEmulatorWarning() {\r\n function attachBanner() {\r\n const el = document.createElement('p');\r\n const sty = el.style;\r\n el.innerText =\r\n 'Running in emulator mode. Do not use with production credentials.';\r\n sty.position = 'fixed';\r\n sty.width = '100%';\r\n sty.backgroundColor = '#ffffff';\r\n sty.border = '.1em solid #000000';\r\n sty.color = '#b50000';\r\n sty.bottom = '0px';\r\n sty.left = '0px';\r\n sty.margin = '0px';\r\n sty.zIndex = '10000';\r\n sty.textAlign = 'center';\r\n el.classList.add('firebase-emulator-warning');\r\n document.body.appendChild(el);\r\n }\r\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\r\n console.info('WARNING: You are using the Auth Emulator,' +\r\n ' which is intended for local testing only. Do not use with' +\r\n ' production credentials.');\r\n }\r\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\r\n if (document.readyState === 'loading') {\r\n window.addEventListener('DOMContentLoaded', attachBanner);\r\n }\r\n else {\r\n attachBanner();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by an {@link AuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /**\r\n * The authentication provider ID for the credential.\r\n *\r\n * @remarks\r\n * For example, 'facebook.com', or 'google.com'.\r\n */\r\n providerId, \r\n /**\r\n * The authentication sign in method for the credential.\r\n *\r\n * @remarks\r\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\r\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\r\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\r\n */\r\n signInMethod) {\r\n this.providerId = providerId;\r\n this.signInMethod = signInMethod;\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n *\r\n * @returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _linkToIdToken(_auth, _idToken) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function resetPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:resetPassword\" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function updateEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function applyActionCode$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithPassword(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPassword\" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendOobCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendOobCode\" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendEmailVerification$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendPasswordResetEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendSignInLinkToEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function verifyAndChangeEmail(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithEmailLink$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithEmailLinkForLinking(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\r\n * {@link ProviderId}.PASSWORD\r\n *\r\n * @remarks\r\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /** @internal */\r\n _email, \r\n /** @internal */\r\n _password, signInMethod, \r\n /** @internal */\r\n _tenantId = null) {\r\n super(\"password\" /* ProviderId.PASSWORD */, signInMethod);\r\n this._email = _email;\r\n this._password = _password;\r\n this._tenantId = _tenantId;\r\n }\r\n /** @internal */\r\n static _fromEmailAndPassword(email, password) {\r\n return new EmailAuthCredential(email, password, \"password\" /* SignInMethod.EMAIL_PASSWORD */);\r\n }\r\n /** @internal */\r\n static _fromEmailAndCode(email, oobCode, tenantId = null) {\r\n return new EmailAuthCredential(email, oobCode, \"emailLink\" /* SignInMethod.EMAIL_LINK */, tenantId);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n email: this._email,\r\n password: this._password,\r\n signInMethod: this.signInMethod,\r\n tenantId: this._tenantId\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\r\n *\r\n * @param json - Either `object` or the stringified representation of the object. When string is\r\n * provided, `JSON.parse` would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {\r\n if (obj.signInMethod === \"password\" /* SignInMethod.EMAIL_PASSWORD */) {\r\n return this._fromEmailAndPassword(obj.email, obj.password);\r\n }\r\n else if (obj.signInMethod === \"emailLink\" /* SignInMethod.EMAIL_LINK */) {\r\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\r\n }\r\n }\r\n return null;\r\n }\r\n /** @internal */\r\n async _getIdTokenResponse(auth) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n return signInWithPassword(auth, {\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password\r\n });\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLink$1(auth, {\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n async _linkToIdToken(auth, idToken) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n return updateEmailPassword(auth, {\r\n idToken,\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password\r\n });\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLinkForLinking(auth, {\r\n idToken,\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return this._getIdTokenResponse(auth);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithIdp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithIdp\" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI$1 = 'http://localhost';\r\n/**\r\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass OAuthCredential extends AuthCredential {\r\n constructor() {\r\n super(...arguments);\r\n this.pendingToken = null;\r\n }\r\n /** @internal */\r\n static _fromParams(params) {\r\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\r\n if (params.idToken || params.accessToken) {\r\n // OAuth 2 and either ID token or access token.\r\n if (params.idToken) {\r\n cred.idToken = params.idToken;\r\n }\r\n if (params.accessToken) {\r\n cred.accessToken = params.accessToken;\r\n }\r\n // Add nonce if available and no pendingToken is present.\r\n if (params.nonce && !params.pendingToken) {\r\n cred.nonce = params.nonce;\r\n }\r\n if (params.pendingToken) {\r\n cred.pendingToken = params.pendingToken;\r\n }\r\n }\r\n else if (params.oauthToken && params.oauthTokenSecret) {\r\n // OAuth 1 and OAuth token with token secret\r\n cred.accessToken = params.oauthToken;\r\n cred.secret = params.oauthTokenSecret;\r\n }\r\n else {\r\n _fail(\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n return cred;\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n idToken: this.idToken,\r\n accessToken: this.accessToken,\r\n secret: this.secret,\r\n nonce: this.nonce,\r\n pendingToken: this.pendingToken,\r\n providerId: this.providerId,\r\n signInMethod: this.signInMethod\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod } = obj, rest = __rest(obj, [\"providerId\", \"signInMethod\"]);\r\n if (!providerId || !signInMethod) {\r\n return null;\r\n }\r\n const cred = new OAuthCredential(providerId, signInMethod);\r\n cred.idToken = rest.idToken || undefined;\r\n cred.accessToken = rest.accessToken || undefined;\r\n cred.secret = rest.secret;\r\n cred.nonce = rest.nonce;\r\n cred.pendingToken = rest.pendingToken || null;\r\n return cred;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n buildRequest() {\r\n const request = {\r\n requestUri: IDP_REQUEST_URI$1,\r\n returnSecureToken: true\r\n };\r\n if (this.pendingToken) {\r\n request.pendingToken = this.pendingToken;\r\n }\r\n else {\r\n const postBody = {};\r\n if (this.idToken) {\r\n postBody['id_token'] = this.idToken;\r\n }\r\n if (this.accessToken) {\r\n postBody['access_token'] = this.accessToken;\r\n }\r\n if (this.secret) {\r\n postBody['oauth_token_secret'] = this.secret;\r\n }\r\n postBody['providerId'] = this.providerId;\r\n if (this.nonce && !this.pendingToken) {\r\n postBody['nonce'] = this.nonce;\r\n }\r\n request.postBody = querystring(postBody);\r\n }\r\n return request;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function sendPhoneVerificationCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendVerificationCode\" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithPhoneNumber$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function linkWithPhoneNumber$1(auth, request) {\r\n const response = await _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n if (response.temporaryProof) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, response);\r\n }\r\n return response;\r\n}\r\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */\r\n};\r\nasync function verifyPhoneNumberForExisting(auth, request) {\r\n const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents the credentials returned by {@link PhoneAuthProvider}.\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"phone\" /* ProviderId.PHONE */, \"phone\" /* SignInMethod.PHONE */);\r\n this.params = params;\r\n }\r\n /** @internal */\r\n static _fromVerification(verificationId, verificationCode) {\r\n return new PhoneAuthCredential({ verificationId, verificationCode });\r\n }\r\n /** @internal */\r\n static _fromTokenResponse(phoneNumber, temporaryProof) {\r\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _makeVerificationRequest() {\r\n const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;\r\n if (temporaryProof && phoneNumber) {\r\n return { temporaryProof, phoneNumber };\r\n }\r\n return {\r\n sessionInfo: verificationId,\r\n code: verificationCode\r\n };\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n const obj = {\r\n providerId: this.providerId\r\n };\r\n if (this.params.phoneNumber) {\r\n obj.phoneNumber = this.params.phoneNumber;\r\n }\r\n if (this.params.temporaryProof) {\r\n obj.temporaryProof = this.params.temporaryProof;\r\n }\r\n if (this.params.verificationCode) {\r\n obj.verificationCode = this.params.verificationCode;\r\n }\r\n if (this.params.verificationId) {\r\n obj.verificationId = this.params.verificationId;\r\n }\r\n return obj;\r\n }\r\n /** Generates a phone credential based on a plain object or a JSON string. */\r\n static fromJSON(json) {\r\n if (typeof json === 'string') {\r\n json = JSON.parse(json);\r\n }\r\n const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;\r\n if (!verificationCode &&\r\n !verificationId &&\r\n !phoneNumber &&\r\n !temporaryProof) {\r\n return null;\r\n }\r\n return new PhoneAuthCredential({\r\n verificationId,\r\n verificationCode,\r\n phoneNumber,\r\n temporaryProof\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Maps the mode string in action code URL to Action Code Info operation.\r\n *\r\n * @param mode\r\n */\r\nfunction parseMode(mode) {\r\n switch (mode) {\r\n case 'recoverEmail':\r\n return \"RECOVER_EMAIL\" /* ActionCodeOperation.RECOVER_EMAIL */;\r\n case 'resetPassword':\r\n return \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */;\r\n case 'signIn':\r\n return \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n case 'verifyEmail':\r\n return \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */;\r\n case 'verifyAndChangeEmail':\r\n return \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;\r\n case 'revertSecondFactorAddition':\r\n return \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;\r\n default:\r\n return null;\r\n }\r\n}\r\n/**\r\n * Helper to parse FDL links\r\n *\r\n * @param url\r\n */\r\nfunction parseDeepLink(url) {\r\n const link = querystringDecode(extractQuerystring(url))['link'];\r\n // Double link case (automatic redirect).\r\n const doubleDeepLink = link\r\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\r\n : null;\r\n // iOS custom scheme links.\r\n const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];\r\n const iOSDoubleDeepLink = iOSDeepLink\r\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\r\n : null;\r\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * A utility class to parse email action URLs such as password reset, email verification,\r\n * email link sign in, etc.\r\n *\r\n * @public\r\n */\r\nclass ActionCodeURL {\r\n /**\r\n * @param actionLink - The link from which to extract the URL.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @internal\r\n */\r\n constructor(actionLink) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const searchParams = querystringDecode(extractQuerystring(actionLink));\r\n const apiKey = (_a = searchParams[\"apiKey\" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;\r\n const code = (_b = searchParams[\"oobCode\" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;\r\n const operation = parseMode((_c = searchParams[\"mode\" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);\r\n // Validate API key, code and mode.\r\n _assert(apiKey && code && operation, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.apiKey = apiKey;\r\n this.operation = operation;\r\n this.code = code;\r\n this.continueUrl = (_d = searchParams[\"continueUrl\" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;\r\n this.languageCode = (_e = searchParams[\"languageCode\" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;\r\n this.tenantId = (_f = searchParams[\"tenantId\" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;\r\n }\r\n /**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\r\n * otherwise returns null.\r\n *\r\n * @param link - The email action link string.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @public\r\n */\r\n static parseLink(link) {\r\n const actionLink = parseDeepLink(link);\r\n try {\r\n return new ActionCodeURL(actionLink);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if\r\n * the link is valid, otherwise returns null.\r\n *\r\n * @public\r\n */\r\nfunction parseActionCodeURL(link) {\r\n return ActionCodeURL.parseLink(link);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating {@link EmailAuthCredential}.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthProvider {\r\n constructor() {\r\n /**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\n this.providerId = EmailAuthProvider.PROVIDER_ID;\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and password.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credential(email, password);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\r\n * ```\r\n *\r\n * @param email - Email address.\r\n * @param password - User account password.\r\n * @returns The auth provider credential.\r\n */\r\n static credential(email, password) {\r\n return EmailAuthCredential._fromEmailAndPassword(email, password);\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\r\n * email link operation.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * await sendSignInLinkToEmail(auth, email);\r\n * // Obtain emailLink from user.\r\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance used to verify the link.\r\n * @param email - Email address.\r\n * @param emailLink - Sign-in email link.\r\n * @returns - The auth provider credential.\r\n */\r\n static credentialWithLink(email, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n _assert(actionCodeUrl, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);\r\n }\r\n}\r\n/**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\nEmailAuthProvider.PROVIDER_ID = \"password\" /* ProviderId.PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\r\n */\r\nEmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = \"password\" /* SignInMethod.EMAIL_PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_LINK.\r\n */\r\nEmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = \"emailLink\" /* SignInMethod.EMAIL_LINK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\r\n *\r\n * This class is not meant to be instantiated directly.\r\n *\r\n * @public\r\n */\r\nclass FederatedAuthProvider {\r\n /**\r\n * Constructor for generic OAuth providers.\r\n *\r\n * @param providerId - Provider for which credentials should be generated.\r\n */\r\n constructor(providerId) {\r\n this.providerId = providerId;\r\n /** @internal */\r\n this.defaultLanguageCode = null;\r\n /** @internal */\r\n this.customParameters = {};\r\n }\r\n /**\r\n * Set the language gode.\r\n *\r\n * @param languageCode - language code\r\n */\r\n setDefaultLanguage(languageCode) {\r\n this.defaultLanguageCode = languageCode;\r\n }\r\n /**\r\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\r\n * operations.\r\n *\r\n * @remarks\r\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\r\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\r\n *\r\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\r\n */\r\n setCustomParameters(customOAuthParameters) {\r\n this.customParameters = customOAuthParameters;\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of {@link CustomParameters}.\r\n */\r\n getCustomParameters() {\r\n return this.customParameters;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Common code to all OAuth providers. This is separate from the\r\n * {@link OAuthProvider} so that child providers (like\r\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\r\n * Instead, they rely on a static `credential` method.\r\n */\r\nclass BaseOAuthProvider extends FederatedAuthProvider {\r\n constructor() {\r\n super(...arguments);\r\n /** @internal */\r\n this.scopes = [];\r\n }\r\n /**\r\n * Add an OAuth scope to the credential.\r\n *\r\n * @param scope - Provider OAuth scope to add.\r\n */\r\n addScope(scope) {\r\n // If not already added, add scope to list.\r\n if (!this.scopes.includes(scope)) {\r\n this.scopes.push(scope);\r\n }\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of OAuth scopes.\r\n */\r\n getScopes() {\r\n return [...this.scopes];\r\n }\r\n}\r\n/**\r\n * Provider for generating generic {@link OAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new OAuthProvider('google.com');\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new OAuthProvider('google.com');\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass OAuthProvider extends BaseOAuthProvider {\r\n /**\r\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n _assert('providerId' in obj && 'signInMethod' in obj, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return OAuthCredential._fromParams(obj);\r\n }\r\n /**\r\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\r\n *\r\n * @remarks\r\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\r\n * the raw nonce must match the nonce field in the ID token.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `googleUser` from the onsuccess Google Sign In callback.\r\n * // Initialize a generate OAuth provider with a `google.com` providerId.\r\n * const provider = new OAuthProvider('google.com');\r\n * const credential = provider.credential({\r\n * idToken: googleUser.getAuthResponse().id_token,\r\n * });\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param params - Either the options object containing the ID token, access token and raw nonce\r\n * or the ID token string.\r\n */\r\n credential(params) {\r\n return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));\r\n }\r\n /** An internal credential method that accepts more permissive options */\r\n _credential(params) {\r\n _assert(params.idToken || params.accessToken, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n // For OAuthCredential, sign in method is same as providerId.\r\n return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;\r\n if (!oauthAccessToken &&\r\n !oauthTokenSecret &&\r\n !oauthIdToken &&\r\n !pendingToken) {\r\n return null;\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n try {\r\n return new OAuthProvider(providerId)._credential({\r\n idToken: oauthIdToken,\r\n accessToken: oauthAccessToken,\r\n nonce,\r\n pendingToken\r\n });\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('user_birthday');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * provider.addScope('user_birthday');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass FacebookAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"facebook.com\" /* ProviderId.FACEBOOK */);\r\n }\r\n /**\r\n * Creates a credential for Facebook.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `event` from the Facebook auth.authResponseChange callback.\r\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param accessToken - Facebook access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: FacebookAuthProvider.PROVIDER_ID,\r\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return FacebookAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.FACEBOOK. */\r\nFacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = \"facebook.com\" /* SignInMethod.FACEBOOK */;\r\n/** Always set to {@link ProviderId}.FACEBOOK. */\r\nFacebookAuthProvider.PROVIDER_ID = \"facebook.com\" /* ProviderId.FACEBOOK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GoogleAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GoogleAuthProvider();\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass GoogleAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"google.com\" /* ProviderId.GOOGLE */);\r\n this.addScope('profile');\r\n }\r\n /**\r\n * Creates a credential for Google. At least one of ID token and access token is required.\r\n *\r\n * @example\r\n * ```javascript\r\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\r\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param idToken - Google ID token.\r\n * @param accessToken - Google access token.\r\n */\r\n static credential(idToken, accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GoogleAuthProvider.PROVIDER_ID,\r\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\r\n idToken,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GoogleAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken } = tokenResponse;\r\n if (!oauthIdToken && !oauthAccessToken) {\r\n // This could be an oauth 1 credential or a phone credential\r\n return null;\r\n }\r\n try {\r\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GOOGLE. */\r\nGoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = \"google.com\" /* SignInMethod.GOOGLE */;\r\n/** Always set to {@link ProviderId}.GOOGLE. */\r\nGoogleAuthProvider.PROVIDER_ID = \"google.com\" /* ProviderId.GOOGLE */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\r\n *\r\n * @remarks\r\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\r\n * the {@link signInWithPopup} handler:\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GithubAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('repo');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GithubAuthProvider();\r\n * provider.addScope('repo');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass GithubAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"github.com\" /* ProviderId.GITHUB */);\r\n }\r\n /**\r\n * Creates a credential for Github.\r\n *\r\n * @param accessToken - Github access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GithubAuthProvider.PROVIDER_ID,\r\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GithubAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GITHUB. */\r\nGithubAuthProvider.GITHUB_SIGN_IN_METHOD = \"github.com\" /* SignInMethod.GITHUB */;\r\n/** Always set to {@link ProviderId}.GITHUB. */\r\nGithubAuthProvider.PROVIDER_ID = \"github.com\" /* ProviderId.GITHUB */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI = 'http://localhost';\r\n/**\r\n * @public\r\n */\r\nclass SAMLAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(providerId, pendingToken) {\r\n super(providerId, providerId);\r\n this.pendingToken = pendingToken;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n signInMethod: this.signInMethod,\r\n providerId: this.providerId,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod, pendingToken } = obj;\r\n if (!providerId ||\r\n !signInMethod ||\r\n !pendingToken ||\r\n providerId !== signInMethod) {\r\n return null;\r\n }\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n /**\r\n * Helper static method to avoid exposing the constructor to end users.\r\n *\r\n * @internal\r\n */\r\n static _create(providerId, pendingToken) {\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n buildRequest() {\r\n return {\r\n requestUri: IDP_REQUEST_URI,\r\n returnSecureToken: true,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SAML_PROVIDER_PREFIX = 'saml.';\r\n/**\r\n * An {@link AuthProvider} for SAML.\r\n *\r\n * @public\r\n */\r\nclass SAMLAuthProvider extends FederatedAuthProvider {\r\n /**\r\n * Constructor. The providerId must start with \"saml.\"\r\n * @param providerId - SAML provider ID.\r\n */\r\n constructor(providerId) {\r\n _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n super(providerId);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\r\n * successful SAML flow completes.\r\n *\r\n * @remarks\r\n *\r\n * For example, to get an {@link AuthCredential}, you could write the\r\n * following code:\r\n *\r\n * ```js\r\n * const userCredential = await signInWithPopup(auth, samlProvider);\r\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\r\n * ```\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n /**\r\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const credential = SAMLAuthCredential.fromJSON(json);\r\n _assert(credential, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return credential;\r\n }\r\n static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { pendingToken, providerId } = tokenResponse;\r\n if (!pendingToken || !providerId) {\r\n return null;\r\n }\r\n try {\r\n return SAMLAuthCredential._create(providerId, pendingToken);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new TwitterAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new TwitterAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass TwitterAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"twitter.com\" /* ProviderId.TWITTER */);\r\n }\r\n /**\r\n * Creates a credential for Twitter.\r\n *\r\n * @param token - Twitter access token.\r\n * @param secret - Twitter secret.\r\n */\r\n static credential(token, secret) {\r\n return OAuthCredential._fromParams({\r\n providerId: TwitterAuthProvider.PROVIDER_ID,\r\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\r\n oauthToken: token,\r\n oauthTokenSecret: secret\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return TwitterAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthAccessToken, oauthTokenSecret } = tokenResponse;\r\n if (!oauthAccessToken || !oauthTokenSecret) {\r\n return null;\r\n }\r\n try {\r\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.TWITTER. */\r\nTwitterAuthProvider.TWITTER_SIGN_IN_METHOD = \"twitter.com\" /* SignInMethod.TWITTER */;\r\n/** Always set to {@link ProviderId}.TWITTER. */\r\nTwitterAuthProvider.PROVIDER_ID = \"twitter.com\" /* ProviderId.TWITTER */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signUp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserCredentialImpl {\r\n constructor(params) {\r\n this.user = params.user;\r\n this.providerId = params.providerId;\r\n this._tokenResponse = params._tokenResponse;\r\n this.operationType = params.operationType;\r\n }\r\n static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {\r\n const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);\r\n const providerId = providerIdForResponse(idTokenResponse);\r\n const userCred = new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: idTokenResponse,\r\n operationType\r\n });\r\n return userCred;\r\n }\r\n static async _forOperation(user, operationType, response) {\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n const providerId = providerIdForResponse(response);\r\n return new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: response,\r\n operationType\r\n });\r\n }\r\n}\r\nfunction providerIdForResponse(response) {\r\n if (response.providerId) {\r\n return response.providerId;\r\n }\r\n if ('phoneNumber' in response) {\r\n return \"phone\" /* ProviderId.PHONE */;\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in as an anonymous user.\r\n *\r\n * @remarks\r\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\r\n * new anonymous user identity will be created and returned.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nasync function signInAnonymously(auth) {\r\n var _a;\r\n const authInternal = _castAuth(auth);\r\n await authInternal._initializationPromise;\r\n if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {\r\n // If an anonymous user is already signed in, no need to sign them in again.\r\n return new UserCredentialImpl({\r\n user: authInternal.currentUser,\r\n providerId: null,\r\n operationType: \"signIn\" /* OperationType.SIGN_IN */\r\n });\r\n }\r\n const response = await signUp(authInternal, {\r\n returnSecureToken: true\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response, true);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorError extends FirebaseError {\r\n constructor(auth, error, operationType, user) {\r\n var _a;\r\n super(error.code, error.message);\r\n this.operationType = operationType;\r\n this.user = user;\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, MultiFactorError.prototype);\r\n this.customData = {\r\n appName: auth.name,\r\n tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,\r\n _serverResponse: error.customData._serverResponse,\r\n operationType\r\n };\r\n }\r\n static _fromErrorAndOperation(auth, error, operationType, user) {\r\n return new MultiFactorError(auth, error, operationType, user);\r\n }\r\n}\r\nfunction _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {\r\n const idTokenProvider = operationType === \"reauthenticate\" /* OperationType.REAUTHENTICATE */\r\n ? credential._getReauthenticationResolver(auth)\r\n : credential._getIdTokenResponse(auth);\r\n return idTokenProvider.catch(error => {\r\n if (error.code === `auth/${\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */}`) {\r\n throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Takes a set of UserInfo provider data and converts it to a set of names\r\n */\r\nfunction providerDataAsNames(providerData) {\r\n return new Set(providerData\r\n .map(({ providerId }) => providerId)\r\n .filter(pid => !!pid));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Unlinks a provider from a user account.\r\n *\r\n * @param user - The user.\r\n * @param providerId - The provider to unlink.\r\n *\r\n * @public\r\n */\r\nasync function unlink(user, providerId) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(true, userInternal, providerId);\r\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\r\n idToken: await userInternal.getIdToken(),\r\n deleteProvider: [providerId]\r\n });\r\n const providersLeft = providerDataAsNames(providerUserInfo || []);\r\n userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));\r\n if (!providersLeft.has(\"phone\" /* ProviderId.PHONE */)) {\r\n userInternal.phoneNumber = null;\r\n }\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n return userInternal;\r\n}\r\nasync function _link$1(user, credential, bypassAuthState = false) {\r\n const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);\r\n return UserCredentialImpl._forOperation(user, \"link\" /* OperationType.LINK */, response);\r\n}\r\nasync function _assertLinkedStatus(expected, user, provider) {\r\n await _reloadWithoutSaving(user);\r\n const providerIds = providerDataAsNames(user.providerData);\r\n const code = expected === false\r\n ? \"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */\r\n : \"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */;\r\n _assert(providerIds.has(provider) === expected, user.auth, code);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reauthenticate(user, credential, bypassAuthState = false) {\r\n const { auth } = user;\r\n const operationType = \"reauthenticate\" /* OperationType.REAUTHENTICATE */;\r\n try {\r\n const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);\r\n _assert(response.idToken, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const parsed = _parseToken(response.idToken);\r\n _assert(parsed, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const { sub: localId } = parsed;\r\n _assert(user.uid === localId, auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n return UserCredentialImpl._forOperation(user, operationType, response);\r\n }\r\n catch (e) {\r\n // Convert user deleted error into user mismatch\r\n if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${\"user-not-found\" /* AuthErrorCode.USER_DELETED */}`) {\r\n _fail(auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n }\r\n throw e;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _signInWithCredential(auth, credential, bypassAuthState = false) {\r\n const operationType = \"signIn\" /* OperationType.SIGN_IN */;\r\n const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);\r\n if (!bypassAuthState) {\r\n await auth._updateCurrentUser(userCredential.user);\r\n }\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCredential(auth, credential) {\r\n return _signInWithCredential(_castAuth(auth), credential);\r\n}\r\n/**\r\n * Links the user account with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function linkWithCredential(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, credential.providerId);\r\n return _link$1(userInternal, credential);\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\r\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithCredential(user, credential) {\r\n return _reauthenticate(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithCustomToken$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithCustomToken\" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in using a custom token.\r\n *\r\n * @remarks\r\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\r\n * be generated by an auth backend using the\r\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\r\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\r\n *\r\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param customToken - The custom token to sign in with.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCustomToken(auth, customToken) {\r\n const authInternal = _castAuth(auth);\r\n const response = await signInWithCustomToken$1(authInternal, {\r\n token: customToken,\r\n returnSecureToken: true\r\n });\r\n const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(cred.user);\r\n return cred;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorInfoImpl {\r\n constructor(factorId, response) {\r\n this.factorId = factorId;\r\n this.uid = response.mfaEnrollmentId;\r\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\r\n this.displayName = response.displayName;\r\n }\r\n static _fromServerResponse(auth, enrollment) {\r\n if ('phoneInfo' in enrollment) {\r\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n return _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n}\r\nclass PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"phone\" /* FactorId.PHONE */, response);\r\n this.phoneNumber = response.phoneInfo;\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new PhoneMultiFactorInfoImpl(enrollment);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {\r\n var _a;\r\n _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, \"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */);\r\n _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\r\n actionCodeSettings.dynamicLinkDomain.length > 0, auth, \"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);\r\n request.continueUrl = actionCodeSettings.url;\r\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\r\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\r\n if (actionCodeSettings.iOS) {\r\n _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, \"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);\r\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\r\n }\r\n if (actionCodeSettings.android) {\r\n _assert(actionCodeSettings.android.packageName.length > 0, auth, \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);\r\n request.androidInstallApp = actionCodeSettings.android.installApp;\r\n request.androidMinimumVersionCode =\r\n actionCodeSettings.android.minimumVersion;\r\n request.androidPackageName = actionCodeSettings.android.packageName;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a password reset email to the given email address.\r\n *\r\n * @remarks\r\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\r\n * the email sent to the user, along with the new password specified by the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain code from user.\r\n * await confirmPasswordReset('user@example.com', code);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendPasswordResetEmail(auth, email, actionCodeSettings) {\r\n const authModular = getModularInstance(auth);\r\n const request = {\r\n requestType: \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */,\r\n email\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);\r\n }\r\n await sendPasswordResetEmail$1(authModular, request);\r\n}\r\n/**\r\n * Completes the password reset process, given a confirmation code and new password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A confirmation code sent to the user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nasync function confirmPasswordReset(auth, oobCode, newPassword) {\r\n await resetPassword(getModularInstance(auth), {\r\n oobCode,\r\n newPassword\r\n });\r\n // Do not return the email.\r\n}\r\n/**\r\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function applyActionCode(auth, oobCode) {\r\n await applyActionCode$1(getModularInstance(auth), { oobCode });\r\n}\r\n/**\r\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns metadata about the code.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function checkActionCode(auth, oobCode) {\r\n const authModular = getModularInstance(auth);\r\n const response = await resetPassword(authModular, { oobCode });\r\n // Email could be empty only if the request type is EMAIL_SIGNIN or\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // New email should not be empty if the request type is\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // Multi-factor info could not be empty if the request type is\r\n // REVERT_SECOND_FACTOR_ADDITION.\r\n const operation = response.requestType;\r\n _assert(operation, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n switch (operation) {\r\n case \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */:\r\n break;\r\n case \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:\r\n _assert(response.newEmail, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n break;\r\n case \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:\r\n _assert(response.mfaInfo, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // fall through\r\n default:\r\n _assert(response.email, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n // The multi-factor info for revert second factor addition\r\n let multiFactorInfo = null;\r\n if (response.mfaInfo) {\r\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);\r\n }\r\n return {\r\n data: {\r\n email: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.newEmail\r\n : response.email) || null,\r\n previousEmail: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.email\r\n : response.newEmail) || null,\r\n multiFactorInfo\r\n },\r\n operation\r\n };\r\n}\r\n/**\r\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns the user's email address if valid.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param code - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function verifyPasswordResetCode(auth, code) {\r\n const { data } = await checkActionCode(getModularInstance(auth), code);\r\n // Email should always be present since a code was sent to it\r\n return data.email;\r\n}\r\n/**\r\n * Creates a new user account associated with the specified email address and password.\r\n *\r\n * @remarks\r\n * On successful creation of the user account, this user will also be signed in to your application.\r\n *\r\n * User account creation can fail if the account already exists or the password is invalid.\r\n *\r\n * Note: The email address acts as a unique identifier for the user and enables an email-based\r\n * password reset. This function will create a new user account and set the initial user password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param password - The user's chosen password.\r\n *\r\n * @public\r\n */\r\nasync function createUserWithEmailAndPassword(auth, email, password) {\r\n const authInternal = _castAuth(auth);\r\n const response = await signUp(authInternal, {\r\n returnSecureToken: true,\r\n email,\r\n password\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and password.\r\n *\r\n * @remarks\r\n * Fails with an error if the email address and password do not match.\r\n *\r\n * Note: The user's password is NOT the password used to access the user's email account. The\r\n * email address serves as a unique identifier for the user, and the password is used to access\r\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The users email address.\r\n * @param password - The users password.\r\n *\r\n * @public\r\n */\r\nfunction signInWithEmailAndPassword(auth, email, password) {\r\n return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a sign-in email link to the user with the specified email.\r\n *\r\n * @remarks\r\n * The sign-in operation has to always be completed in the app unlike other out of band email\r\n * actions (password reset and email verifications). This is because, at the end of the flow,\r\n * the user is expected to be signed in and their Auth state persisted within the app.\r\n *\r\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\r\n * address and the email link supplied in the email sent to the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param authInternal - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendSignInLinkToEmail(auth, email, actionCodeSettings) {\r\n const authModular = getModularInstance(auth);\r\n const request = {\r\n requestType: \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */,\r\n email\r\n };\r\n _assert(actionCodeSettings.handleCodeInApp, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);\r\n }\r\n await sendSignInLinkToEmail$1(authModular, request);\r\n}\r\n/**\r\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nfunction isSignInWithEmailLink(auth, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and sign-in email link.\r\n *\r\n * @remarks\r\n * If no link is passed, the link is inferred from the current URL.\r\n *\r\n * Fails with an error if the email address is invalid or OTP in email link expires.\r\n *\r\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nasync function signInWithEmailLink(auth, email, emailLink) {\r\n const authModular = getModularInstance(auth);\r\n const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());\r\n // Check if the tenant ID in the email link matches the tenant ID on Auth\r\n // instance.\r\n _assert(credential._tenantId === (authModular.tenantId || null), authModular, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n return signInWithCredential(authModular, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createAuthUri(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:createAuthUri\" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Gets the list of possible sign in methods for the given email address.\r\n *\r\n * @remarks\r\n * This is useful to differentiate methods of sign-in for the same provider, eg.\r\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\r\n * {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n *\r\n * @public\r\n */\r\nasync function fetchSignInMethodsForEmail(auth, email) {\r\n // createAuthUri returns an error if continue URI is not http or https.\r\n // For environments like Cordova, Chrome extensions, native frameworks, file\r\n // systems, etc, use http://localhost as continue URL.\r\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\r\n const request = {\r\n identifier: email,\r\n continueUri\r\n };\r\n const { signinMethods } = await createAuthUri(getModularInstance(auth), request);\r\n return signinMethods || [];\r\n}\r\n/**\r\n * Sends a verification email to a user.\r\n *\r\n * @remarks\r\n * The verification process is completed by calling {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendEmailVerification(user, actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendEmailVerification(user, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */,\r\n idToken\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await sendEmailVerification$1(userInternal.auth, request);\r\n if (email !== user.email) {\r\n await user.reload();\r\n }\r\n}\r\n/**\r\n * Sends a verification email to a new email address.\r\n *\r\n * @remarks\r\n * The user's email will be updated to the new one after being verified.\r\n *\r\n * If you have a custom email action handler, you can complete the verification process by calling\r\n * {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address to be verified before update.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,\r\n idToken,\r\n newEmail\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await verifyAndChangeEmail(userInternal.auth, request);\r\n if (email !== user.email) {\r\n // If the local copy of the email on user is outdated, reload the\r\n // user.\r\n await user.reload();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateProfile$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates a user's profile data.\r\n *\r\n * @param user - The user.\r\n * @param profile - The profile's `displayName` and `photoURL` to update.\r\n *\r\n * @public\r\n */\r\nasync function updateProfile(user, { displayName, photoURL: photoUrl }) {\r\n if (displayName === undefined && photoUrl === undefined) {\r\n return;\r\n }\r\n const userInternal = getModularInstance(user);\r\n const idToken = await userInternal.getIdToken();\r\n const profileRequest = {\r\n idToken,\r\n displayName,\r\n photoUrl,\r\n returnSecureToken: true\r\n };\r\n const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));\r\n userInternal.displayName = response.displayName || null;\r\n userInternal.photoURL = response.photoUrl || null;\r\n // Update the password provider as well\r\n const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === \"password\" /* ProviderId.PASSWORD */);\r\n if (passwordProvider) {\r\n passwordProvider.displayName = userInternal.displayName;\r\n passwordProvider.photoURL = userInternal.photoURL;\r\n }\r\n await userInternal._updateTokensIfNecessary(response);\r\n}\r\n/**\r\n * Updates the user's email address.\r\n *\r\n * @remarks\r\n * An email will be sent to the original email address (if it was set) that allows to revoke the\r\n * email address change, in order to protect them from account hijacking.\r\n *\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address.\r\n *\r\n * @public\r\n */\r\nfunction updateEmail(user, newEmail) {\r\n return updateEmailOrPassword(getModularInstance(user), newEmail, null);\r\n}\r\n/**\r\n * Updates the user's password.\r\n *\r\n * @remarks\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nfunction updatePassword(user, newPassword) {\r\n return updateEmailOrPassword(getModularInstance(user), null, newPassword);\r\n}\r\nasync function updateEmailOrPassword(user, email, password) {\r\n const { auth } = user;\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n idToken,\r\n returnSecureToken: true\r\n };\r\n if (email) {\r\n request.email = email;\r\n }\r\n if (password) {\r\n request.password = password;\r\n }\r\n const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Parse the `AdditionalUserInfo` from the ID token response.\r\n *\r\n */\r\nfunction _fromIdTokenResponse(idTokenResponse) {\r\n var _a, _b;\r\n if (!idTokenResponse) {\r\n return null;\r\n }\r\n const { providerId } = idTokenResponse;\r\n const profile = idTokenResponse.rawUserInfo\r\n ? JSON.parse(idTokenResponse.rawUserInfo)\r\n : {};\r\n const isNewUser = idTokenResponse.isNewUser ||\r\n idTokenResponse.kind === \"identitytoolkit#SignupNewUserResponse\" /* IdTokenResponseKind.SignupNewUser */;\r\n if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {\r\n const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];\r\n if (signInProvider) {\r\n const filteredProviderId = signInProvider !== \"anonymous\" /* ProviderId.ANONYMOUS */ &&\r\n signInProvider !== \"custom\" /* ProviderId.CUSTOM */\r\n ? signInProvider\r\n : null;\r\n // Uses generic class in accordance with the legacy SDK.\r\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\r\n }\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n switch (providerId) {\r\n case \"facebook.com\" /* ProviderId.FACEBOOK */:\r\n return new FacebookAdditionalUserInfo(isNewUser, profile);\r\n case \"github.com\" /* ProviderId.GITHUB */:\r\n return new GithubAdditionalUserInfo(isNewUser, profile);\r\n case \"google.com\" /* ProviderId.GOOGLE */:\r\n return new GoogleAdditionalUserInfo(isNewUser, profile);\r\n case \"twitter.com\" /* ProviderId.TWITTER */:\r\n return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);\r\n case \"custom\" /* ProviderId.CUSTOM */:\r\n case \"anonymous\" /* ProviderId.ANONYMOUS */:\r\n return new GenericAdditionalUserInfo(isNewUser, null);\r\n default:\r\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\r\n }\r\n}\r\nclass GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile = {}) {\r\n this.isNewUser = isNewUser;\r\n this.providerId = providerId;\r\n this.profile = profile;\r\n }\r\n}\r\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile, username) {\r\n super(isNewUser, providerId, profile);\r\n this.username = username;\r\n }\r\n}\r\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"facebook.com\" /* ProviderId.FACEBOOK */, profile);\r\n }\r\n}\r\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"github.com\" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);\r\n }\r\n}\r\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"google.com\" /* ProviderId.GOOGLE */, profile);\r\n }\r\n}\r\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile, screenName) {\r\n super(isNewUser, \"twitter.com\" /* ProviderId.TWITTER */, profile, screenName);\r\n }\r\n}\r\n/**\r\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\r\n *\r\n * @param userCredential - The user credential.\r\n *\r\n * @public\r\n */\r\nfunction getAdditionalUserInfo(userCredential) {\r\n const { user, _tokenResponse } = userCredential;\r\n if (user.isAnonymous && !_tokenResponse) {\r\n // Handle the special case where signInAnonymously() gets called twice.\r\n // No network call is made so there's nothing to actually fill this in\r\n return {\r\n providerId: null,\r\n isNewUser: false,\r\n profile: null\r\n };\r\n }\r\n return _fromIdTokenResponse(_tokenResponse);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Non-optional auth methods.\r\n/**\r\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\r\n * `Auth` session and applies this type of persistence for future sign-in requests, including\r\n * sign-in with redirect requests.\r\n *\r\n * @remarks\r\n * This makes it easy for a user signing in to specify whether their session should be\r\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\r\n * that are shared by other users or have sensitive data.\r\n *\r\n * @example\r\n * ```javascript\r\n * setPersistence(auth, browserSessionPersistence);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param persistence - The {@link Persistence} to use.\r\n * @returns A `Promise` that resolves once the persistence change has completed\r\n *\r\n * @public\r\n */\r\nfunction setPersistence(auth, persistence) {\r\n return getModularInstance(auth).setPersistence(persistence);\r\n}\r\n/**\r\n * Adds an observer for changes to the signed-in user's ID token.\r\n *\r\n * @remarks\r\n * This includes sign-in, sign-out, and token refresh events.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onIdTokenChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Adds a blocking callback that runs before an auth state change\r\n * sets a new user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param callback - callback triggered before new user value is set.\r\n * If this throws, it blocks the user from being set.\r\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\r\n * callback throws, allowing you to undo any side effects.\r\n */\r\nfunction beforeAuthStateChanged(auth, callback, onAbort) {\r\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\r\n}\r\n/**\r\n * Adds an observer for changes to the user's sign-in state.\r\n *\r\n * @remarks\r\n * To keep the old behavior, see {@link onIdTokenChanged}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onAuthStateChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Sets the current language to the default device/browser preference.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction useDeviceLanguage(auth) {\r\n getModularInstance(auth).useDeviceLanguage();\r\n}\r\n/**\r\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\r\n * {@link Auth} instance.\r\n *\r\n * @remarks\r\n * A new instance copy of the user provided will be made and set as currentUser.\r\n *\r\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\r\n * like other sign in methods.\r\n *\r\n * The operation fails with an error if the user to be updated belongs to a different Firebase\r\n * project.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param user - The new {@link User}.\r\n *\r\n * @public\r\n */\r\nfunction updateCurrentUser(auth, user) {\r\n return getModularInstance(auth).updateCurrentUser(user);\r\n}\r\n/**\r\n * Signs out the current user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction signOut(auth) {\r\n return getModularInstance(auth).signOut();\r\n}\r\n/**\r\n * Deletes and signs out the user.\r\n *\r\n * @remarks\r\n * Important: this is a security-sensitive operation that requires the user to have recently\r\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function deleteUser(user) {\r\n return getModularInstance(user).delete();\r\n}\n\nclass MultiFactorSessionImpl {\r\n constructor(type, credential, auth) {\r\n this.type = type;\r\n this.credential = credential;\r\n this.auth = auth;\r\n }\r\n static _fromIdtoken(idToken, auth) {\r\n return new MultiFactorSessionImpl(\"enroll\" /* MultiFactorSessionType.ENROLL */, idToken, auth);\r\n }\r\n static _fromMfaPendingCredential(mfaPendingCredential) {\r\n return new MultiFactorSessionImpl(\"signin\" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);\r\n }\r\n toJSON() {\r\n const key = this.type === \"enroll\" /* MultiFactorSessionType.ENROLL */\r\n ? 'idToken'\r\n : 'pendingCredential';\r\n return {\r\n multiFactorSession: {\r\n [key]: this.credential\r\n }\r\n };\r\n }\r\n static fromJSON(obj) {\r\n var _a, _b;\r\n if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {\r\n if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {\r\n return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);\r\n }\r\n else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {\r\n return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);\r\n }\r\n }\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorResolverImpl {\r\n constructor(session, hints, signInResolver) {\r\n this.session = session;\r\n this.hints = hints;\r\n this.signInResolver = signInResolver;\r\n }\r\n /** @internal */\r\n static _fromError(authExtern, error) {\r\n const auth = _castAuth(authExtern);\r\n const serverResponse = error.customData._serverResponse;\r\n const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));\r\n _assert(serverResponse.mfaPendingCredential, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);\r\n return new MultiFactorResolverImpl(session, hints, async (assertion) => {\r\n const mfaResponse = await assertion._process(auth, session);\r\n // Clear out the unneeded fields from the old login response\r\n delete serverResponse.mfaInfo;\r\n delete serverResponse.mfaPendingCredential;\r\n // Use in the new token & refresh token in the old response\r\n const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });\r\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\r\n switch (error.operationType) {\r\n case \"signIn\" /* OperationType.SIGN_IN */:\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);\r\n await auth._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n case \"reauthenticate\" /* OperationType.REAUTHENTICATE */:\r\n _assert(error.user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n });\r\n }\r\n async resolveSignIn(assertionExtern) {\r\n const assertion = assertionExtern;\r\n return this.signInResolver(assertion);\r\n }\r\n}\r\n/**\r\n * Provides a {@link MultiFactorResolver} suitable for completion of a\r\n * multi-factor flow.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\r\n * reauthentication operation.\r\n *\r\n * @public\r\n */\r\nfunction getMultiFactorResolver(auth, error) {\r\n var _a;\r\n const authModular = getModularInstance(auth);\r\n const errorInternal = error;\r\n _assert(error.customData.operationType, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction withdrawMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:withdraw\" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));\r\n}\n\nclass MultiFactorUserImpl {\r\n constructor(user) {\r\n this.user = user;\r\n this.enrolledFactors = [];\r\n user._onReload(userInfo => {\r\n if (userInfo.mfaInfo) {\r\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));\r\n }\r\n });\r\n }\r\n static _fromUser(user) {\r\n return new MultiFactorUserImpl(user);\r\n }\r\n async getSession() {\r\n return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user.auth);\r\n }\r\n async enroll(assertionExtern, displayName) {\r\n const assertion = assertionExtern;\r\n const session = (await this.getSession());\r\n const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));\r\n // New tokens will be issued after enrollment of the new second factors.\r\n // They need to be updated on the user.\r\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\r\n // The user needs to be reloaded to get the new multi-factor information\r\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\r\n // will be updated.\r\n return this.user.reload();\r\n }\r\n async unenroll(infoOrUid) {\r\n const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\r\n const idToken = await this.user.getIdToken();\r\n const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {\r\n idToken,\r\n mfaEnrollmentId\r\n }));\r\n // Remove the second factor from the user's list.\r\n this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);\r\n // Depending on whether the backend decided to revoke the user's session,\r\n // the tokenResponse may be empty. If the tokens were not updated (and they\r\n // are now invalid), reloading the user will discover this and invalidate\r\n // the user's state accordingly.\r\n await this.user._updateTokensIfNecessary(idTokenResponse);\r\n try {\r\n await this.user.reload();\r\n }\r\n catch (e) {\r\n if ((e === null || e === void 0 ? void 0 : e.code) !== `auth/${\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */}`) {\r\n throw e;\r\n }\r\n }\r\n }\r\n}\r\nconst multiFactorUserCache = new WeakMap();\r\n/**\r\n * The {@link MultiFactorUser} corresponding to the user.\r\n *\r\n * @remarks\r\n * This is used to access all multi-factor properties and operations related to the user.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nfunction multiFactor(user) {\r\n const userModular = getModularInstance(user);\r\n if (!multiFactorUserCache.has(userModular)) {\r\n multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));\r\n }\r\n return multiFactorUserCache.get(userModular);\r\n}\n\nconst STORAGE_AVAILABLE_KEY = '__sak';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// There are two different browser persistence types: local and session.\r\n// Both have the same implementation but use a different underlying storage\r\n// object.\r\nclass BrowserPersistenceClass {\r\n constructor(storageRetriever, type) {\r\n this.storageRetriever = storageRetriever;\r\n this.type = type;\r\n }\r\n _isAvailable() {\r\n try {\r\n if (!this.storage) {\r\n return Promise.resolve(false);\r\n }\r\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\r\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\r\n return Promise.resolve(true);\r\n }\r\n catch (_a) {\r\n return Promise.resolve(false);\r\n }\r\n }\r\n _set(key, value) {\r\n this.storage.setItem(key, JSON.stringify(value));\r\n return Promise.resolve();\r\n }\r\n _get(key) {\r\n const json = this.storage.getItem(key);\r\n return Promise.resolve(json ? JSON.parse(json) : null);\r\n }\r\n _remove(key) {\r\n this.storage.removeItem(key);\r\n return Promise.resolve();\r\n }\r\n get storage() {\r\n return this.storageRetriever();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _iframeCannotSyncWebStorage() {\r\n const ua = getUA();\r\n return _isSafari(ua) || _isIOS(ua);\r\n}\r\n// The polling period in case events are not supported\r\nconst _POLLING_INTERVAL_MS$1 = 1000;\r\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\r\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\r\nclass BrowserLocalPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.localStorage, \"LOCAL\" /* PersistenceType.LOCAL */);\r\n this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n // Safari or iOS browser and embedded in an iframe.\r\n this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();\r\n // Whether to use polling instead of depending on window events\r\n this.fallbackToPolling = _isMobileBrowser();\r\n this._shouldAllowMigration = true;\r\n }\r\n forAllChangedKeys(cb) {\r\n // Check all keys with listeners on them.\r\n for (const key of Object.keys(this.listeners)) {\r\n // Get value from localStorage.\r\n const newValue = this.storage.getItem(key);\r\n const oldValue = this.localCache[key];\r\n // If local map value does not match, trigger listener with storage event.\r\n // Differentiate this simulated event from the real storage event.\r\n if (newValue !== oldValue) {\r\n cb(key, oldValue, newValue);\r\n }\r\n }\r\n }\r\n onStorageEvent(event, poll = false) {\r\n // Key would be null in some situations, like when localStorage is cleared\r\n if (!event.key) {\r\n this.forAllChangedKeys((key, _oldValue, newValue) => {\r\n this.notifyListeners(key, newValue);\r\n });\r\n return;\r\n }\r\n const key = event.key;\r\n // Check the mechanism how this event was detected.\r\n // The first event will dictate the mechanism to be used.\r\n if (poll) {\r\n // Environment detects storage changes via polling.\r\n // Remove storage event listener to prevent possible event duplication.\r\n this.detachListener();\r\n }\r\n else {\r\n // Environment detects storage changes via storage event listener.\r\n // Remove polling listener to prevent possible event duplication.\r\n this.stopPolling();\r\n }\r\n // Safari embedded iframe. Storage event will trigger with the delta\r\n // changes but no changes will be applied to the iframe localStorage.\r\n if (this.safariLocalStorageNotSynced) {\r\n // Get current iframe page value.\r\n const storedValue = this.storage.getItem(key);\r\n // Value not synchronized, synchronize manually.\r\n if (event.newValue !== storedValue) {\r\n if (event.newValue !== null) {\r\n // Value changed from current value.\r\n this.storage.setItem(key, event.newValue);\r\n }\r\n else {\r\n // Current value deleted.\r\n this.storage.removeItem(key);\r\n }\r\n }\r\n else if (this.localCache[key] === event.newValue && !poll) {\r\n // Already detected and processed, do not trigger listeners again.\r\n return;\r\n }\r\n }\r\n const triggerListeners = () => {\r\n // Keep local map up to date in case storage event is triggered before\r\n // poll.\r\n const storedValue = this.storage.getItem(key);\r\n if (!poll && this.localCache[key] === storedValue) {\r\n // Real storage event which has already been detected, do nothing.\r\n // This seems to trigger in some IE browsers for some reason.\r\n return;\r\n }\r\n this.notifyListeners(key, storedValue);\r\n };\r\n const storedValue = this.storage.getItem(key);\r\n if (_isIE10() &&\r\n storedValue !== event.newValue &&\r\n event.newValue !== event.oldValue) {\r\n // IE 10 has this weird bug where a storage event would trigger with the\r\n // correct key, oldValue and newValue but localStorage.getItem(key) does\r\n // not yield the updated value until a few milliseconds. This ensures\r\n // this recovers from that situation.\r\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\r\n }\r\n else {\r\n triggerListeners();\r\n }\r\n }\r\n notifyListeners(key, value) {\r\n this.localCache[key] = value;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(value ? JSON.parse(value) : value);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(() => {\r\n this.forAllChangedKeys((key, oldValue, newValue) => {\r\n this.onStorageEvent(new StorageEvent('storage', {\r\n key,\r\n oldValue,\r\n newValue\r\n }), \r\n /* poll */ true);\r\n });\r\n }, _POLLING_INTERVAL_MS$1);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n attachListener() {\r\n window.addEventListener('storage', this.boundEventHandler);\r\n }\r\n detachListener() {\r\n window.removeEventListener('storage', this.boundEventHandler);\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n // Whether browser can detect storage event when it had already been pushed to the background.\r\n // This may happen in some mobile browsers. A localStorage change in the foreground window\r\n // will not be detected in the background window via the storage event.\r\n // This was detected in iOS 7.x mobile browsers\r\n if (this.fallbackToPolling) {\r\n this.startPolling();\r\n }\r\n else {\r\n this.attachListener();\r\n }\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n this.localCache[key] = this.storage.getItem(key);\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.detachListener();\r\n this.stopPolling();\r\n }\r\n }\r\n // Update local cache on base operations:\r\n async _set(key, value) {\r\n await super._set(key, value);\r\n this.localCache[key] = JSON.stringify(value);\r\n }\r\n async _get(key) {\r\n const value = await super._get(key);\r\n this.localCache[key] = JSON.stringify(value);\r\n return value;\r\n }\r\n async _remove(key) {\r\n await super._remove(key);\r\n delete this.localCache[key];\r\n }\r\n}\r\nBrowserLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserLocalPersistence = BrowserLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass BrowserSessionPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.sessionStorage, \"SESSION\" /* PersistenceType.SESSION */);\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n}\r\nBrowserSessionPersistence.type = 'SESSION';\r\n/**\r\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserSessionPersistence = BrowserSessionPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\r\n *\r\n * @param promises - Array of promises to wait on.\r\n */\r\nfunction _allSettled(promises) {\r\n return Promise.all(promises.map(async (promise) => {\r\n try {\r\n const value = await promise;\r\n return {\r\n fulfilled: true,\r\n value\r\n };\r\n }\r\n catch (reason) {\r\n return {\r\n fulfilled: false,\r\n reason\r\n };\r\n }\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface class for receiving messages.\r\n *\r\n */\r\nclass Receiver {\r\n constructor(eventTarget) {\r\n this.eventTarget = eventTarget;\r\n this.handlersMap = {};\r\n this.boundEventHandler = this.handleEvent.bind(this);\r\n }\r\n /**\r\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\r\n *\r\n * @param eventTarget - An event target (such as window or self) through which the underlying\r\n * messages will be received.\r\n */\r\n static _getInstance(eventTarget) {\r\n // The results are stored in an array since objects can't be keys for other\r\n // objects. In addition, setting a unique property on an event target as a\r\n // hash map key may not be allowed due to CORS restrictions.\r\n const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));\r\n if (existingInstance) {\r\n return existingInstance;\r\n }\r\n const newInstance = new Receiver(eventTarget);\r\n this.receivers.push(newInstance);\r\n return newInstance;\r\n }\r\n isListeningto(eventTarget) {\r\n return this.eventTarget === eventTarget;\r\n }\r\n /**\r\n * Fans out a MessageEvent to the appropriate listeners.\r\n *\r\n * @remarks\r\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\r\n * finished processing.\r\n *\r\n * @param event - The MessageEvent.\r\n *\r\n */\r\n async handleEvent(event) {\r\n const messageEvent = event;\r\n const { eventId, eventType, data } = messageEvent.data;\r\n const handlers = this.handlersMap[eventType];\r\n if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {\r\n return;\r\n }\r\n messageEvent.ports[0].postMessage({\r\n status: \"ack\" /* _Status.ACK */,\r\n eventId,\r\n eventType\r\n });\r\n const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));\r\n const response = await _allSettled(promises);\r\n messageEvent.ports[0].postMessage({\r\n status: \"done\" /* _Status.DONE */,\r\n eventId,\r\n eventType,\r\n response\r\n });\r\n }\r\n /**\r\n * Subscribe an event handler for a particular event.\r\n *\r\n * @param eventType - Event name to subscribe to.\r\n * @param eventHandler - The event handler which should receive the events.\r\n *\r\n */\r\n _subscribe(eventType, eventHandler) {\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.addEventListener('message', this.boundEventHandler);\r\n }\r\n if (!this.handlersMap[eventType]) {\r\n this.handlersMap[eventType] = new Set();\r\n }\r\n this.handlersMap[eventType].add(eventHandler);\r\n }\r\n /**\r\n * Unsubscribe an event handler from a particular event.\r\n *\r\n * @param eventType - Event name to unsubscribe from.\r\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\r\n *\r\n */\r\n _unsubscribe(eventType, eventHandler) {\r\n if (this.handlersMap[eventType] && eventHandler) {\r\n this.handlersMap[eventType].delete(eventHandler);\r\n }\r\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\r\n delete this.handlersMap[eventType];\r\n }\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\r\n }\r\n }\r\n}\r\nReceiver.receivers = [];\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _generateEventId(prefix = '', digits = 10) {\r\n let random = '';\r\n for (let i = 0; i < digits; i++) {\r\n random += Math.floor(Math.random() * 10);\r\n }\r\n return prefix + random;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface for sending messages and waiting for a completion response.\r\n *\r\n */\r\nclass Sender {\r\n constructor(target) {\r\n this.target = target;\r\n this.handlers = new Set();\r\n }\r\n /**\r\n * Unsubscribe the handler and remove it from our tracking Set.\r\n *\r\n * @param handler - The handler to unsubscribe.\r\n */\r\n removeMessageHandler(handler) {\r\n if (handler.messageChannel) {\r\n handler.messageChannel.port1.removeEventListener('message', handler.onMessage);\r\n handler.messageChannel.port1.close();\r\n }\r\n this.handlers.delete(handler);\r\n }\r\n /**\r\n * Send a message to the Receiver located at {@link target}.\r\n *\r\n * @remarks\r\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\r\n * receiver has had a chance to fully process the event.\r\n *\r\n * @param eventType - Type of event to send.\r\n * @param data - The payload of the event.\r\n * @param timeout - Timeout for waiting on an ACK from the receiver.\r\n *\r\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\r\n */\r\n async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {\r\n const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\r\n if (!messageChannel) {\r\n throw new Error(\"connection_unavailable\" /* _MessageError.CONNECTION_UNAVAILABLE */);\r\n }\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let completionTimer;\r\n let handler;\r\n return new Promise((resolve, reject) => {\r\n const eventId = _generateEventId('', 20);\r\n messageChannel.port1.start();\r\n const ackTimer = setTimeout(() => {\r\n reject(new Error(\"unsupported_event\" /* _MessageError.UNSUPPORTED_EVENT */));\r\n }, timeout);\r\n handler = {\r\n messageChannel,\r\n onMessage(event) {\r\n const messageEvent = event;\r\n if (messageEvent.data.eventId !== eventId) {\r\n return;\r\n }\r\n switch (messageEvent.data.status) {\r\n case \"ack\" /* _Status.ACK */:\r\n // The receiver should ACK first.\r\n clearTimeout(ackTimer);\r\n completionTimer = setTimeout(() => {\r\n reject(new Error(\"timeout\" /* _MessageError.TIMEOUT */));\r\n }, 3000 /* _TimeoutDuration.COMPLETION */);\r\n break;\r\n case \"done\" /* _Status.DONE */:\r\n // Once the receiver's handlers are finished we will get the results.\r\n clearTimeout(completionTimer);\r\n resolve(messageEvent.data.response);\r\n break;\r\n default:\r\n clearTimeout(ackTimer);\r\n clearTimeout(completionTimer);\r\n reject(new Error(\"invalid_response\" /* _MessageError.INVALID_RESPONSE */));\r\n break;\r\n }\r\n }\r\n };\r\n this.handlers.add(handler);\r\n messageChannel.port1.addEventListener('message', handler.onMessage);\r\n this.target.postMessage({\r\n eventType,\r\n eventId,\r\n data\r\n }, [messageChannel.port2]);\r\n }).finally(() => {\r\n if (handler) {\r\n this.removeMessageHandler(handler);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Lazy accessor for window, since the compat layer won't tree shake this out,\r\n * we need to make sure not to mess with window unless we have to\r\n */\r\nfunction _window() {\r\n return window;\r\n}\r\nfunction _setWindowLocation(url) {\r\n _window().location.href = url;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _isWorker() {\r\n return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\r\n typeof _window()['importScripts'] === 'function');\r\n}\r\nasync function _getActiveServiceWorker() {\r\n if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {\r\n return null;\r\n }\r\n try {\r\n const registration = await navigator.serviceWorker.ready;\r\n return registration.active;\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n}\r\nfunction _getServiceWorkerController() {\r\n var _a;\r\n return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;\r\n}\r\nfunction _getWorkerGlobalScope() {\r\n return _isWorker() ? self : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebaseLocalStorageDb';\r\nconst DB_VERSION = 1;\r\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\r\nconst DB_DATA_KEYPATH = 'fbase_key';\r\n/**\r\n * Promise wrapper for IDBRequest\r\n *\r\n * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6\r\n *\r\n */\r\nclass DBPromise {\r\n constructor(request) {\r\n this.request = request;\r\n }\r\n toPromise() {\r\n return new Promise((resolve, reject) => {\r\n this.request.addEventListener('success', () => {\r\n resolve(this.request.result);\r\n });\r\n this.request.addEventListener('error', () => {\r\n reject(this.request.error);\r\n });\r\n });\r\n }\r\n}\r\nfunction getObjectStore(db, isReadWrite) {\r\n return db\r\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\r\n .objectStore(DB_OBJECTSTORE_NAME);\r\n}\r\nfunction _deleteDatabase() {\r\n const request = indexedDB.deleteDatabase(DB_NAME);\r\n return new DBPromise(request).toPromise();\r\n}\r\nfunction _openDatabase() {\r\n const request = indexedDB.open(DB_NAME, DB_VERSION);\r\n return new Promise((resolve, reject) => {\r\n request.addEventListener('error', () => {\r\n reject(request.error);\r\n });\r\n request.addEventListener('upgradeneeded', () => {\r\n const db = request.result;\r\n try {\r\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n });\r\n request.addEventListener('success', async () => {\r\n const db = request.result;\r\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\r\n // same time. The only way to recover seems to be deleting the database\r\n // and re-initializing it.\r\n // https://github.com/firebase/firebase-js-sdk/issues/634\r\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\r\n // Need to close the database or else you get a `blocked` event\r\n db.close();\r\n await _deleteDatabase();\r\n resolve(await _openDatabase());\r\n }\r\n else {\r\n resolve(db);\r\n }\r\n });\r\n });\r\n}\r\nasync function _putObject(db, key, value) {\r\n const request = getObjectStore(db, true).put({\r\n [DB_DATA_KEYPATH]: key,\r\n value\r\n });\r\n return new DBPromise(request).toPromise();\r\n}\r\nasync function getObject(db, key) {\r\n const request = getObjectStore(db, false).get(key);\r\n const data = await new DBPromise(request).toPromise();\r\n return data === undefined ? null : data.value;\r\n}\r\nfunction _deleteObject(db, key) {\r\n const request = getObjectStore(db, true).delete(key);\r\n return new DBPromise(request).toPromise();\r\n}\r\nconst _POLLING_INTERVAL_MS = 800;\r\nconst _TRANSACTION_RETRY_COUNT = 3;\r\nclass IndexedDBLocalPersistence {\r\n constructor() {\r\n this.type = \"LOCAL\" /* PersistenceType.LOCAL */;\r\n this._shouldAllowMigration = true;\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n this.pendingWrites = 0;\r\n this.receiver = null;\r\n this.sender = null;\r\n this.serviceWorkerReceiverAvailable = false;\r\n this.activeServiceWorker = null;\r\n // Fire & forget the service worker registration as it may never resolve\r\n this._workerInitializationPromise =\r\n this.initializeServiceWorkerMessaging().then(() => { }, () => { });\r\n }\r\n async _openDb() {\r\n if (this.db) {\r\n return this.db;\r\n }\r\n this.db = await _openDatabase();\r\n return this.db;\r\n }\r\n async _withRetries(op) {\r\n let numAttempts = 0;\r\n while (true) {\r\n try {\r\n const db = await this._openDb();\r\n return await op(db);\r\n }\r\n catch (e) {\r\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\r\n throw e;\r\n }\r\n if (this.db) {\r\n this.db.close();\r\n this.db = undefined;\r\n }\r\n // TODO: consider adding exponential backoff\r\n }\r\n }\r\n }\r\n /**\r\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\r\n * postMessage interface to send these events to the worker ourselves.\r\n */\r\n async initializeServiceWorkerMessaging() {\r\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n }\r\n /**\r\n * As the worker we should listen to events from the main window.\r\n */\r\n async initializeReceiver() {\r\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n // Refresh from persistence if we receive a KeyChanged message.\r\n this.receiver._subscribe(\"keyChanged\" /* _EventType.KEY_CHANGED */, async (_origin, data) => {\r\n const keys = await this._poll();\r\n return {\r\n keyProcessed: keys.includes(data.key)\r\n };\r\n });\r\n // Let the sender know that we are listening so they give us more timeout.\r\n this.receiver._subscribe(\"ping\" /* _EventType.PING */, async (_origin, _data) => {\r\n return [\"keyChanged\" /* _EventType.KEY_CHANGED */];\r\n });\r\n }\r\n /**\r\n * As the main window, we should let the worker know when keys change (set and remove).\r\n *\r\n * @remarks\r\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\r\n * may not resolve.\r\n */\r\n async initializeSender() {\r\n var _a, _b;\r\n // Check to see if there's an active service worker.\r\n this.activeServiceWorker = await _getActiveServiceWorker();\r\n if (!this.activeServiceWorker) {\r\n return;\r\n }\r\n this.sender = new Sender(this.activeServiceWorker);\r\n // Ping the service worker to check what events they can handle.\r\n const results = await this.sender._send(\"ping\" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);\r\n if (!results) {\r\n return;\r\n }\r\n if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&\r\n ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(\"keyChanged\" /* _EventType.KEY_CHANGED */))) {\r\n this.serviceWorkerReceiverAvailable = true;\r\n }\r\n }\r\n /**\r\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\r\n * worker will just trigger a full sync anyway.\r\n *\r\n * @remarks\r\n * For now, we only support one service worker per page.\r\n *\r\n * @param key - Storage key which changed.\r\n */\r\n async notifyServiceWorker(key) {\r\n if (!this.sender ||\r\n !this.activeServiceWorker ||\r\n _getServiceWorkerController() !== this.activeServiceWorker) {\r\n return;\r\n }\r\n try {\r\n await this.sender._send(\"keyChanged\" /* _EventType.KEY_CHANGED */, { key }, \r\n // Use long timeout if receiver has previously responded to a ping from us.\r\n this.serviceWorkerReceiverAvailable\r\n ? 800 /* _TimeoutDuration.LONG_ACK */\r\n : 50 /* _TimeoutDuration.ACK */);\r\n }\r\n catch (_a) {\r\n // This is a best effort approach. Ignore errors.\r\n }\r\n }\r\n async _isAvailable() {\r\n try {\r\n if (!indexedDB) {\r\n return false;\r\n }\r\n const db = await _openDatabase();\r\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\r\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\r\n return true;\r\n }\r\n catch (_a) { }\r\n return false;\r\n }\r\n async _withPendingWrite(write) {\r\n this.pendingWrites++;\r\n try {\r\n await write();\r\n }\r\n finally {\r\n this.pendingWrites--;\r\n }\r\n }\r\n async _set(key, value) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _putObject(db, key, value));\r\n this.localCache[key] = value;\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _get(key) {\r\n const obj = (await this._withRetries((db) => getObject(db, key)));\r\n this.localCache[key] = obj;\r\n return obj;\r\n }\r\n async _remove(key) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _deleteObject(db, key));\r\n delete this.localCache[key];\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _poll() {\r\n // TODO: check if we need to fallback if getAll is not supported\r\n const result = await this._withRetries((db) => {\r\n const getAllRequest = getObjectStore(db, false).getAll();\r\n return new DBPromise(getAllRequest).toPromise();\r\n });\r\n if (!result) {\r\n return [];\r\n }\r\n // If we have pending writes in progress abort, we'll get picked up on the next poll\r\n if (this.pendingWrites !== 0) {\r\n return [];\r\n }\r\n const keys = [];\r\n const keysInResult = new Set();\r\n for (const { fbase_key: key, value } of result) {\r\n keysInResult.add(key);\r\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\r\n this.notifyListeners(key, value);\r\n keys.push(key);\r\n }\r\n }\r\n for (const localKey of Object.keys(this.localCache)) {\r\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\r\n // Deleted\r\n this.notifyListeners(localKey, null);\r\n keys.push(localKey);\r\n }\r\n }\r\n return keys;\r\n }\r\n notifyListeners(key, newValue) {\r\n this.localCache[key] = newValue;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(newValue);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.startPolling();\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n void this._get(key); // This can happen in the background async and we can return immediately.\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.stopPolling();\r\n }\r\n }\r\n}\r\nIndexedDBLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst indexedDBLocalPersistence = IndexedDBLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:start\" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getRecaptchaParams(auth) {\r\n return ((await _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/recaptchaParams\" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getScriptParentElement() {\r\n var _a, _b;\r\n return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;\r\n}\r\nfunction _loadJS(url) {\r\n // TODO: consider adding timeout support & cancellation\r\n return new Promise((resolve, reject) => {\r\n const el = document.createElement('script');\r\n el.setAttribute('src', url);\r\n el.onload = resolve;\r\n el.onerror = e => {\r\n const error = _createError(\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n error.customData = e;\r\n reject(error);\r\n };\r\n el.type = 'text/javascript';\r\n el.charset = 'UTF-8';\r\n getScriptParentElement().appendChild(el);\r\n });\r\n}\r\nfunction _generateCallbackName(prefix) {\r\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _SOLVE_TIME_MS = 500;\r\nconst _EXPIRATION_TIME_MS = 60000;\r\nconst _WIDGET_ID_START = 1000000000000;\r\nclass MockReCaptcha {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.counter = _WIDGET_ID_START;\r\n this._widgets = new Map();\r\n }\r\n render(container, parameters) {\r\n const id = this.counter;\r\n this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));\r\n this.counter++;\r\n return id;\r\n }\r\n reset(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());\r\n this._widgets.delete(id);\r\n }\r\n getResponse(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';\r\n }\r\n async execute(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());\r\n return '';\r\n }\r\n}\r\nclass MockWidget {\r\n constructor(containerOrId, appName, params) {\r\n this.params = params;\r\n this.timerId = null;\r\n this.deleted = false;\r\n this.responseToken = null;\r\n this.clickHandler = () => {\r\n this.execute();\r\n };\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });\r\n this.container = container;\r\n this.isVisible = this.params.size !== 'invisible';\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n else {\r\n this.container.addEventListener('click', this.clickHandler);\r\n }\r\n }\r\n getResponse() {\r\n this.checkIfDeleted();\r\n return this.responseToken;\r\n }\r\n delete() {\r\n this.checkIfDeleted();\r\n this.deleted = true;\r\n if (this.timerId) {\r\n clearTimeout(this.timerId);\r\n this.timerId = null;\r\n }\r\n this.container.removeEventListener('click', this.clickHandler);\r\n }\r\n execute() {\r\n this.checkIfDeleted();\r\n if (this.timerId) {\r\n return;\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.responseToken = generateRandomAlphaNumericString(50);\r\n const { callback, 'expired-callback': expiredCallback } = this.params;\r\n if (callback) {\r\n try {\r\n callback(this.responseToken);\r\n }\r\n catch (e) { }\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.timerId = null;\r\n this.responseToken = null;\r\n if (expiredCallback) {\r\n try {\r\n expiredCallback();\r\n }\r\n catch (e) { }\r\n }\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n }, _EXPIRATION_TIME_MS);\r\n }, _SOLVE_TIME_MS);\r\n }\r\n checkIfDeleted() {\r\n if (this.deleted) {\r\n throw new Error('reCAPTCHA mock was already deleted!');\r\n }\r\n }\r\n}\r\nfunction generateRandomAlphaNumericString(len) {\r\n const chars = [];\r\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n for (let i = 0; i < len; i++) {\r\n chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));\r\n }\r\n return chars.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// ReCaptcha will load using the same callback, so the callback function needs\r\n// to be kept around\r\nconst _JSLOAD_CALLBACK = _generateCallbackName('rcb');\r\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\r\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\r\n/**\r\n * Loader for the GReCaptcha library. There should only ever be one of this.\r\n */\r\nclass ReCaptchaLoaderImpl {\r\n constructor() {\r\n var _a;\r\n this.hostLanguage = '';\r\n this.counter = 0;\r\n /**\r\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\r\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\r\n * `window.grecaptcha.render()` will not. Another load will add it.\r\n */\r\n this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);\r\n }\r\n load(auth, hl = '') {\r\n _assert(isHostLanguageValid(hl), auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (this.shouldResolveImmediately(hl)) {\r\n return Promise.resolve(_window().grecaptcha);\r\n }\r\n return new Promise((resolve, reject) => {\r\n const networkTimeout = _window().setTimeout(() => {\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, NETWORK_TIMEOUT_DELAY.get());\r\n _window()[_JSLOAD_CALLBACK] = () => {\r\n _window().clearTimeout(networkTimeout);\r\n delete _window()[_JSLOAD_CALLBACK];\r\n const recaptcha = _window().grecaptcha;\r\n if (!recaptcha) {\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n return;\r\n }\r\n // Wrap the greptcha render function so that we know if the developer has\r\n // called it separately\r\n const render = recaptcha.render;\r\n recaptcha.render = (container, params) => {\r\n const widgetId = render(container, params);\r\n this.counter++;\r\n return widgetId;\r\n };\r\n this.hostLanguage = hl;\r\n resolve(recaptcha);\r\n };\r\n const url = `${RECAPTCHA_BASE}?${querystring({\r\n onload: _JSLOAD_CALLBACK,\r\n render: 'explicit',\r\n hl\r\n })}`;\r\n _loadJS(url).catch(() => {\r\n clearTimeout(networkTimeout);\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n });\r\n });\r\n }\r\n clearedOneInstance() {\r\n this.counter--;\r\n }\r\n shouldResolveImmediately(hl) {\r\n var _a;\r\n // We can resolve immediately if:\r\n // • grecaptcha is already defined AND (\r\n // 1. the requested language codes are the same OR\r\n // 2. there exists already a ReCaptcha on the page\r\n // 3. the library was already loaded by the app\r\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\r\n // that are already in the page\r\n return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&\r\n (hl === this.hostLanguage ||\r\n this.counter > 0 ||\r\n this.librarySeparatelyLoaded));\r\n }\r\n}\r\nfunction isHostLanguageValid(hl) {\r\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\r\n}\r\nclass MockReCaptchaLoaderImpl {\r\n async load(auth) {\r\n return new MockReCaptcha(auth);\r\n }\r\n clearedOneInstance() { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\r\nconst DEFAULT_PARAMS = {\r\n theme: 'light',\r\n type: 'image'\r\n};\r\n/**\r\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\r\n *\r\n * @public\r\n */\r\nclass RecaptchaVerifier {\r\n /**\r\n *\r\n * @param containerOrId - The reCAPTCHA container parameter.\r\n *\r\n * @remarks\r\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\r\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\r\n * an element ID. The corresponding element must also must be in the DOM at the time of\r\n * initialization.\r\n *\r\n * @param parameters - The optional reCAPTCHA parameters.\r\n *\r\n * @remarks\r\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\r\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\r\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\r\n * 'invisible'.\r\n *\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n */\r\n constructor(containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS), authExtern) {\r\n this.parameters = parameters;\r\n /**\r\n * The application verifier type.\r\n *\r\n * @remarks\r\n * For a reCAPTCHA verifier, this is 'recaptcha'.\r\n */\r\n this.type = RECAPTCHA_VERIFIER_TYPE;\r\n this.destroyed = false;\r\n this.widgetId = null;\r\n this.tokenChangeListeners = new Set();\r\n this.renderPromise = null;\r\n this.recaptcha = null;\r\n this.auth = _castAuth(authExtern);\r\n this.isInvisible = this.parameters.size === 'invisible';\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.container = container;\r\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\r\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\r\n ? new MockReCaptchaLoaderImpl()\r\n : new ReCaptchaLoaderImpl();\r\n this.validateStartingState();\r\n // TODO: Figure out if sdk version is needed\r\n }\r\n /**\r\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\r\n *\r\n * @returns A Promise for the reCAPTCHA token.\r\n */\r\n async verify() {\r\n this.assertNotDestroyed();\r\n const id = await this.render();\r\n const recaptcha = this.getAssertedRecaptcha();\r\n const response = recaptcha.getResponse(id);\r\n if (response) {\r\n return response;\r\n }\r\n return new Promise(resolve => {\r\n const tokenChange = (token) => {\r\n if (!token) {\r\n return; // Ignore token expirations.\r\n }\r\n this.tokenChangeListeners.delete(tokenChange);\r\n resolve(token);\r\n };\r\n this.tokenChangeListeners.add(tokenChange);\r\n if (this.isInvisible) {\r\n recaptcha.execute(id);\r\n }\r\n });\r\n }\r\n /**\r\n * Renders the reCAPTCHA widget on the page.\r\n *\r\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\r\n */\r\n render() {\r\n try {\r\n this.assertNotDestroyed();\r\n }\r\n catch (e) {\r\n // This method returns a promise. Since it's not async (we want to return the\r\n // _same_ promise if rendering is still occurring), the API surface should\r\n // reject with the error rather than just throw\r\n return Promise.reject(e);\r\n }\r\n if (this.renderPromise) {\r\n return this.renderPromise;\r\n }\r\n this.renderPromise = this.makeRenderPromise().catch(e => {\r\n this.renderPromise = null;\r\n throw e;\r\n });\r\n return this.renderPromise;\r\n }\r\n /** @internal */\r\n _reset() {\r\n this.assertNotDestroyed();\r\n if (this.widgetId !== null) {\r\n this.getAssertedRecaptcha().reset(this.widgetId);\r\n }\r\n }\r\n /**\r\n * Clears the reCAPTCHA widget from the page and destroys the instance.\r\n */\r\n clear() {\r\n this.assertNotDestroyed();\r\n this.destroyed = true;\r\n this._recaptchaLoader.clearedOneInstance();\r\n if (!this.isInvisible) {\r\n this.container.childNodes.forEach(node => {\r\n this.container.removeChild(node);\r\n });\r\n }\r\n }\r\n validateStartingState() {\r\n _assert(!this.parameters.sitekey, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n }\r\n makeTokenCallback(existing) {\r\n return token => {\r\n this.tokenChangeListeners.forEach(listener => listener(token));\r\n if (typeof existing === 'function') {\r\n existing(token);\r\n }\r\n else if (typeof existing === 'string') {\r\n const globalFunc = _window()[existing];\r\n if (typeof globalFunc === 'function') {\r\n globalFunc(token);\r\n }\r\n }\r\n };\r\n }\r\n assertNotDestroyed() {\r\n _assert(!this.destroyed, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n async makeRenderPromise() {\r\n await this.init();\r\n if (!this.widgetId) {\r\n let container = this.container;\r\n if (!this.isInvisible) {\r\n const guaranteedEmpty = document.createElement('div');\r\n container.appendChild(guaranteedEmpty);\r\n container = guaranteedEmpty;\r\n }\r\n this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);\r\n }\r\n return this.widgetId;\r\n }\r\n async init() {\r\n _assert(_isHttpOrHttps() && !_isWorker(), this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n await domReady();\r\n this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);\r\n const siteKey = await getRecaptchaParams(this.auth);\r\n _assert(siteKey, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.parameters.sitekey = siteKey;\r\n }\r\n getAssertedRecaptcha() {\r\n _assert(this.recaptcha, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.recaptcha;\r\n }\r\n}\r\nfunction domReady() {\r\n let resolver = null;\r\n return new Promise(resolve => {\r\n if (document.readyState === 'complete') {\r\n resolve();\r\n return;\r\n }\r\n // Document not ready, wait for load before resolving.\r\n // Save resolver, so we can remove listener in case it was externally\r\n // cancelled.\r\n resolver = () => resolve();\r\n window.addEventListener('load', resolver);\r\n }).catch(e => {\r\n if (resolver) {\r\n window.removeEventListener('load', resolver);\r\n }\r\n throw e;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ConfirmationResultImpl {\r\n constructor(verificationId, onConfirmation) {\r\n this.verificationId = verificationId;\r\n this.onConfirmation = onConfirmation;\r\n }\r\n confirm(verificationCode) {\r\n const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);\r\n return this.onConfirmation(authCredential);\r\n }\r\n}\r\n/**\r\n * Asynchronously signs in using a phone number.\r\n *\r\n * @remarks\r\n * This method sends a code via SMS to the given\r\n * phone number, and returns a {@link ConfirmationResult}. After the user\r\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\r\n * with the code to sign the user in.\r\n *\r\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\r\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\r\n * This function can work on other platforms that do not support the\r\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\r\n * third-party {@link ApplicationVerifier} implementation.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain a verificationCode from the user.\r\n * const credential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {\r\n const authInternal = _castAuth(auth);\r\n const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));\r\n}\r\n/**\r\n * Links the user account with the given phone number.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, \"phone\" /* ProviderId.PHONE */);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh phone credential.\r\n *\r\n * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\r\n *\r\n */\r\nasync function _verifyPhoneNumber(auth, options, verifier) {\r\n var _a;\r\n const recaptchaToken = await verifier.verify();\r\n try {\r\n _assert(typeof recaptchaToken === 'string', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n let phoneInfoOptions;\r\n if (typeof options === 'string') {\r\n phoneInfoOptions = {\r\n phoneNumber: options\r\n };\r\n }\r\n else {\r\n phoneInfoOptions = options;\r\n }\r\n if ('session' in phoneInfoOptions) {\r\n const session = phoneInfoOptions.session;\r\n if ('phoneNumber' in phoneInfoOptions) {\r\n _assert(session.type === \"enroll\" /* MultiFactorSessionType.ENROLL */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollPhoneMfa(auth, {\r\n idToken: session.credential,\r\n phoneEnrollmentInfo: {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneSessionInfo.sessionInfo;\r\n }\r\n else {\r\n _assert(session.type === \"signin\" /* MultiFactorSessionType.SIGN_IN */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||\r\n phoneInfoOptions.multiFactorUid;\r\n _assert(mfaEnrollmentId, auth, \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */);\r\n const response = await startSignInPhoneMfa(auth, {\r\n mfaPendingCredential: session.credential,\r\n mfaEnrollmentId,\r\n phoneSignInInfo: {\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneResponseInfo.sessionInfo;\r\n }\r\n }\r\n else {\r\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n });\r\n return sessionInfo;\r\n }\r\n }\r\n finally {\r\n verifier._reset();\r\n }\r\n}\r\n/**\r\n * Updates the user's phone number.\r\n *\r\n * @example\r\n * ```\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * await updatePhoneNumber(user, phoneCredential);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param credential - A credential authenticating the new phone number.\r\n *\r\n * @public\r\n */\r\nasync function updatePhoneNumber(user, credential) {\r\n await _link$1(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link PhoneAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, phoneCredential);\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthProvider {\r\n /**\r\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\r\n *\r\n */\r\n constructor(auth) {\r\n /** Always set to {@link ProviderId}.PHONE. */\r\n this.providerId = PhoneAuthProvider.PROVIDER_ID;\r\n this.auth = _castAuth(auth);\r\n }\r\n /**\r\n *\r\n * Starts a phone number authentication flow by sending a verification code to the given phone\r\n * number.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\r\n * E.164 format (e.g. +16505550101).\r\n * @param applicationVerifier - For abuse prevention, this method also requires a\r\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\r\n * {@link RecaptchaVerifier}.\r\n *\r\n * @returns A Promise for a verification ID that can be passed to\r\n * {@link PhoneAuthProvider.credential} to identify this flow..\r\n */\r\n verifyPhoneNumber(phoneOptions, applicationVerifier) {\r\n return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));\r\n }\r\n /**\r\n * Creates a phone auth credential, given the verification ID from\r\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\r\n * mobile device.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\r\n * @param verificationCode - The verification code sent to the user's mobile device.\r\n *\r\n * @returns The auth provider credential.\r\n */\r\n static credential(verificationId, verificationCode) {\r\n return PhoneAuthCredential._fromVerification(verificationId, verificationCode);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n const credential = userCredential;\r\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\r\n }\r\n /**\r\n * Returns an {@link AuthCredential} when passed an error.\r\n *\r\n * @remarks\r\n *\r\n * This method works for errors like\r\n * `auth/account-exists-with-different-credentials`. This is useful for\r\n * recovering when attempting to set a user's phone number but the number\r\n * in question is already tied to another account. For example, the following\r\n * code tries to update the current user's phone number, and if that\r\n * fails, links the user with the account associated with that number:\r\n *\r\n * ```js\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\r\n * try {\r\n * const code = ''; // Prompt the user for the verification code\r\n * await updatePhoneNumber(\r\n * auth.currentUser,\r\n * PhoneAuthProvider.credential(verificationId, code));\r\n * } catch (e) {\r\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\r\n * const cred = PhoneAuthProvider.credentialFromError(e);\r\n * await linkWithCredential(auth.currentUser, cred);\r\n * }\r\n * }\r\n *\r\n * // At this point, auth.currentUser.phoneNumber === number.\r\n * ```\r\n *\r\n * @param error - The error to generate a credential from.\r\n */\r\n static credentialFromError(error) {\r\n return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { phoneNumber, temporaryProof } = tokenResponse;\r\n if (phoneNumber && temporaryProof) {\r\n return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);\r\n }\r\n return null;\r\n }\r\n}\r\n/** Always set to {@link ProviderId}.PHONE. */\r\nPhoneAuthProvider.PROVIDER_ID = \"phone\" /* ProviderId.PHONE */;\r\n/** Always set to {@link SignInMethod}.PHONE. */\r\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = \"phone\" /* SignInMethod.PHONE */;\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Chooses a popup/redirect resolver to use. This prefers the override (which\r\n * is directly passed in), and falls back to the property set on the auth\r\n * object. If neither are available, this function errors w/ an argument error.\r\n */\r\nfunction _withDefaultResolver(auth, resolverOverride) {\r\n if (resolverOverride) {\r\n return _getInstance(resolverOverride);\r\n }\r\n _assert(auth._popupRedirectResolver, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return auth._popupRedirectResolver;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass IdpCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"custom\" /* ProviderId.CUSTOM */, \"custom\" /* ProviderId.CUSTOM */);\r\n this.params = params;\r\n }\r\n _getIdTokenResponse(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _linkToIdToken(auth, idToken) {\r\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\r\n }\r\n _getReauthenticationResolver(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _buildIdpRequest(idToken) {\r\n const request = {\r\n requestUri: this.params.requestUri,\r\n sessionId: this.params.sessionId,\r\n postBody: this.params.postBody,\r\n tenantId: this.params.tenantId,\r\n pendingToken: this.params.pendingToken,\r\n returnSecureToken: true,\r\n returnIdpCredential: true\r\n };\r\n if (idToken) {\r\n request.idToken = idToken;\r\n }\r\n return request;\r\n }\r\n}\r\nfunction _signIn(params) {\r\n return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nfunction _reauth(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nasync function _link(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _link$1(user, new IdpCredential(params), params.bypassAuthState);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n */\r\nclass AbstractPopupRedirectOperation {\r\n constructor(auth, filter, resolver, user, bypassAuthState = false) {\r\n this.auth = auth;\r\n this.resolver = resolver;\r\n this.user = user;\r\n this.bypassAuthState = bypassAuthState;\r\n this.pendingPromise = null;\r\n this.eventManager = null;\r\n this.filter = Array.isArray(filter) ? filter : [filter];\r\n }\r\n execute() {\r\n return new Promise(async (resolve, reject) => {\r\n this.pendingPromise = { resolve, reject };\r\n try {\r\n this.eventManager = await this.resolver._initialize(this.auth);\r\n await this.onExecution();\r\n this.eventManager.registerConsumer(this);\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n });\r\n }\r\n async onAuthEvent(event) {\r\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\r\n if (error) {\r\n this.reject(error);\r\n return;\r\n }\r\n const params = {\r\n auth: this.auth,\r\n requestUri: urlResponse,\r\n sessionId: sessionId,\r\n tenantId: tenantId || undefined,\r\n postBody: postBody || undefined,\r\n user: this.user,\r\n bypassAuthState: this.bypassAuthState\r\n };\r\n try {\r\n this.resolve(await this.getIdpTask(type)(params));\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n }\r\n onError(error) {\r\n this.reject(error);\r\n }\r\n getIdpTask(type) {\r\n switch (type) {\r\n case \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */:\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n return _signIn;\r\n case \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n return _link;\r\n case \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return _reauth;\r\n default:\r\n _fail(this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n resolve(cred) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.resolve(cred);\r\n this.unregisterAndCleanUp();\r\n }\r\n reject(error) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.reject(error);\r\n this.unregisterAndCleanUp();\r\n }\r\n unregisterAndCleanUp() {\r\n if (this.eventManager) {\r\n this.eventManager.unregisterConsumer(this);\r\n }\r\n this.pendingPromise = null;\r\n this.cleanUp();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\r\n/**\r\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\r\n *\r\n * @remarks\r\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\r\n * unsuccessful, returns an error object containing additional information about the error.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n *\r\n * @public\r\n */\r\nasync function signInWithPopup(auth, provider, resolver) {\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n const action = new PopupOperation(authInternal, \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\r\n * OAuth flow.\r\n *\r\n * @remarks\r\n * If the reauthentication is successful, the returned result will contain the user and the\r\n * provider's credential.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n * // Reauthenticate using a popup.\r\n * await reauthenticateWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\r\n *\r\n * @remarks\r\n * If the linking is successful, the returned result will contain the user and the provider's credential.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n *\r\n */\r\nclass PopupOperation extends AbstractPopupRedirectOperation {\r\n constructor(auth, filter, provider, resolver, user) {\r\n super(auth, filter, resolver, user);\r\n this.provider = provider;\r\n this.authWindow = null;\r\n this.pollId = null;\r\n if (PopupOperation.currentPopupAction) {\r\n PopupOperation.currentPopupAction.cancel();\r\n }\r\n PopupOperation.currentPopupAction = this;\r\n }\r\n async executeNotNull() {\r\n const result = await this.execute();\r\n _assert(result, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return result;\r\n }\r\n async onExecution() {\r\n debugAssert(this.filter.length === 1, 'Popup operations only handle one event');\r\n const eventId = _generateEventId();\r\n this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor\r\n eventId);\r\n this.authWindow.associatedEvent = eventId;\r\n // Check for web storage support and origin validation _after_ the popup is\r\n // loaded. These operations are slow (~1 second or so) Rather than\r\n // waiting on them before opening the window, optimistically open the popup\r\n // and check for storage support at the same time. If storage support is\r\n // not available, this will cause the whole thing to reject properly. It\r\n // will also close the popup, but since the promise has already rejected,\r\n // the popup closed by user poll will reject into the void.\r\n this.resolver._originValidation(this.auth).catch(e => {\r\n this.reject(e);\r\n });\r\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\r\n if (!isSupported) {\r\n this.reject(_createError(this.auth, \"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));\r\n }\r\n });\r\n // Handle user closure. Notice this does *not* use await\r\n this.pollUserCancellation();\r\n }\r\n get eventId() {\r\n var _a;\r\n return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;\r\n }\r\n cancel() {\r\n this.reject(_createError(this.auth, \"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));\r\n }\r\n cleanUp() {\r\n if (this.authWindow) {\r\n this.authWindow.close();\r\n }\r\n if (this.pollId) {\r\n window.clearTimeout(this.pollId);\r\n }\r\n this.authWindow = null;\r\n this.pollId = null;\r\n PopupOperation.currentPopupAction = null;\r\n }\r\n pollUserCancellation() {\r\n const poll = () => {\r\n var _a, _b;\r\n if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {\r\n // Make sure that there is sufficient time for whatever action to\r\n // complete. The window could have closed but the sign in network\r\n // call could still be in flight.\r\n this.pollId = window.setTimeout(() => {\r\n this.pollId = null;\r\n this.reject(_createError(this.auth, \"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));\r\n }, 2000 /* _Timeout.AUTH_EVENT */);\r\n return;\r\n }\r\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\r\n };\r\n poll();\r\n }\r\n}\r\n// Only one popup is ever shown at once. The lifecycle of the current popup\r\n// can be managed / cancelled by the constructor.\r\nPopupOperation.currentPopupAction = null;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\r\n// We only get one redirect outcome for any one auth, so just store it\r\n// in here.\r\nconst redirectOutcomeMap = new Map();\r\nclass RedirectAction extends AbstractPopupRedirectOperation {\r\n constructor(auth, resolver, bypassAuthState = false) {\r\n super(auth, [\r\n \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,\r\n \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */,\r\n \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */,\r\n \"unknown\" /* AuthEventType.UNKNOWN */\r\n ], resolver, undefined, bypassAuthState);\r\n this.eventId = null;\r\n }\r\n /**\r\n * Override the execute function; if we already have a redirect result, then\r\n * just return it.\r\n */\r\n async execute() {\r\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\r\n if (!readyOutcome) {\r\n try {\r\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);\r\n const result = hasPendingRedirect ? await super.execute() : null;\r\n readyOutcome = () => Promise.resolve(result);\r\n }\r\n catch (e) {\r\n readyOutcome = () => Promise.reject(e);\r\n }\r\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\r\n }\r\n // If we're not bypassing auth state, the ready outcome should be set to\r\n // null.\r\n if (!this.bypassAuthState) {\r\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\r\n }\r\n return readyOutcome();\r\n }\r\n async onAuthEvent(event) {\r\n if (event.type === \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {\r\n return super.onAuthEvent(event);\r\n }\r\n else if (event.type === \"unknown\" /* AuthEventType.UNKNOWN */) {\r\n // This is a sentinel value indicating there's no pending redirect\r\n this.resolve(null);\r\n return;\r\n }\r\n if (event.eventId) {\r\n const user = await this.auth._redirectUserForId(event.eventId);\r\n if (user) {\r\n this.user = user;\r\n return super.onAuthEvent(event);\r\n }\r\n else {\r\n this.resolve(null);\r\n }\r\n }\r\n }\r\n async onExecution() { }\r\n cleanUp() { }\r\n}\r\nasync function _getAndClearPendingRedirectStatus(resolver, auth) {\r\n const key = pendingRedirectKey(auth);\r\n const persistence = resolverPersistence(resolver);\r\n if (!(await persistence._isAvailable())) {\r\n return false;\r\n }\r\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\r\n await persistence._remove(key);\r\n return hasPendingRedirect;\r\n}\r\nasync function _setPendingRedirectStatus(resolver, auth) {\r\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\r\n}\r\nfunction _clearRedirectOutcomes() {\r\n redirectOutcomeMap.clear();\r\n}\r\nfunction _overrideRedirectResult(auth, result) {\r\n redirectOutcomeMap.set(auth._key(), result);\r\n}\r\nfunction resolverPersistence(resolver) {\r\n return _getInstance(resolver._redirectPersistence);\r\n}\r\nfunction pendingRedirectKey(auth) {\r\n return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Authenticates a Firebase client using a full-page redirect flow.\r\n *\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link signInWithRedirect}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction signInWithRedirect(auth, provider, resolver) {\r\n return _signInWithRedirect(auth, provider, resolver);\r\n}\r\nasync function _signInWithRedirect(auth, provider, resolver) {\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await authInternal._initializationPromise;\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, authInternal);\r\n return resolverInternal._openRedirect(authInternal, provider, \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link reauthenticateWithRedirect}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * // Reauthenticate using a redirect.\r\n * await reauthenticateWithRedirect(result.user, provider);\r\n * // This will again trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction reauthenticateWithRedirect(user, provider, resolver) {\r\n return _reauthenticateWithRedirect(user, provider, resolver);\r\n}\r\nasync function _reauthenticateWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link linkWithRedirect}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithRedirect(result.user, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n *\r\n * @public\r\n */\r\nfunction linkWithRedirect(user, provider, resolver) {\r\n return _linkWithRedirect(user, provider, resolver);\r\n}\r\nasync function _linkWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _assertLinkedStatus(false, userInternal, provider.providerId);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\r\n *\r\n * @remarks\r\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\r\n * error. If no redirect operation was called, returns `null`.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function getRedirectResult(auth, resolver) {\r\n await _castAuth(auth)._initializationPromise;\r\n return _getRedirectResult(auth, resolver, false);\r\n}\r\nasync function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {\r\n const authInternal = _castAuth(auth);\r\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\r\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\r\n const result = await action.execute();\r\n if (result && !bypassAuthState) {\r\n delete result.user._redirectEventId;\r\n await authInternal._persistUserIfCurrent(result.user);\r\n await authInternal._setRedirectUser(null, resolverExtern);\r\n }\r\n return result;\r\n}\r\nasync function prepareUserForRedirect(user) {\r\n const eventId = _generateEventId(`${user.uid}:::`);\r\n user._redirectEventId = eventId;\r\n await user.auth._setRedirectUser(user);\r\n await user.auth._persistUserIfCurrent(user);\r\n return eventId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The amount of time to store the UIDs of seen events; this is\r\n// set to 10 min by default\r\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\r\nclass AuthEventManager {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.cachedEventUids = new Set();\r\n this.consumers = new Set();\r\n this.queuedRedirectEvent = null;\r\n this.hasHandledPotentialRedirect = false;\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n registerConsumer(authEventConsumer) {\r\n this.consumers.add(authEventConsumer);\r\n if (this.queuedRedirectEvent &&\r\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {\r\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\r\n this.saveEventToCache(this.queuedRedirectEvent);\r\n this.queuedRedirectEvent = null;\r\n }\r\n }\r\n unregisterConsumer(authEventConsumer) {\r\n this.consumers.delete(authEventConsumer);\r\n }\r\n onEvent(event) {\r\n // Check if the event has already been handled\r\n if (this.hasEventBeenHandled(event)) {\r\n return false;\r\n }\r\n let handled = false;\r\n this.consumers.forEach(consumer => {\r\n if (this.isEventForConsumer(event, consumer)) {\r\n handled = true;\r\n this.sendToConsumer(event, consumer);\r\n this.saveEventToCache(event);\r\n }\r\n });\r\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\r\n // If we've already seen a redirect before, or this is a popup event,\r\n // bail now\r\n return handled;\r\n }\r\n this.hasHandledPotentialRedirect = true;\r\n // If the redirect wasn't handled, hang on to it\r\n if (!handled) {\r\n this.queuedRedirectEvent = event;\r\n handled = true;\r\n }\r\n return handled;\r\n }\r\n sendToConsumer(event, consumer) {\r\n var _a;\r\n if (event.error && !isNullRedirectEvent(event)) {\r\n const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||\r\n \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */;\r\n consumer.onError(_createError(this.auth, code));\r\n }\r\n else {\r\n consumer.onAuthEvent(event);\r\n }\r\n }\r\n isEventForConsumer(event, consumer) {\r\n const eventIdMatches = consumer.eventId === null ||\r\n (!!event.eventId && event.eventId === consumer.eventId);\r\n return consumer.filter.includes(event.type) && eventIdMatches;\r\n }\r\n hasEventBeenHandled(event) {\r\n if (Date.now() - this.lastProcessedEventTime >=\r\n EVENT_DUPLICATION_CACHE_DURATION_MS) {\r\n this.cachedEventUids.clear();\r\n }\r\n return this.cachedEventUids.has(eventUid(event));\r\n }\r\n saveEventToCache(event) {\r\n this.cachedEventUids.add(eventUid(event));\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n}\r\nfunction eventUid(e) {\r\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\r\n}\r\nfunction isNullRedirectEvent({ type, error }) {\r\n return (type === \"unknown\" /* AuthEventType.UNKNOWN */ &&\r\n (error === null || error === void 0 ? void 0 : error.code) === `auth/${\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */}`);\r\n}\r\nfunction isRedirectEvent(event) {\r\n switch (event.type) {\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return true;\r\n case \"unknown\" /* AuthEventType.UNKNOWN */:\r\n return isNullRedirectEvent(event);\r\n default:\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _getProjectConfig(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/projects\" /* Endpoint.GET_PROJECT_CONFIG */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\r\nconst HTTP_REGEX = /^https?/;\r\nasync function _validateOrigin(auth) {\r\n // Skip origin validation if we are in an emulated environment\r\n if (auth.config.emulator) {\r\n return;\r\n }\r\n const { authorizedDomains } = await _getProjectConfig(auth);\r\n for (const domain of authorizedDomains) {\r\n try {\r\n if (matchDomain(domain)) {\r\n return;\r\n }\r\n }\r\n catch (_a) {\r\n // Do nothing if there's a URL error; just continue searching\r\n }\r\n }\r\n // In the old SDK, this error also provides helpful messages.\r\n _fail(auth, \"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */);\r\n}\r\nfunction matchDomain(expected) {\r\n const currentUrl = _getCurrentUrl();\r\n const { protocol, hostname } = new URL(currentUrl);\r\n if (expected.startsWith('chrome-extension://')) {\r\n const ceUrl = new URL(expected);\r\n if (ceUrl.hostname === '' && hostname === '') {\r\n // For some reason we're not parsing chrome URLs properly\r\n return (protocol === 'chrome-extension:' &&\r\n expected.replace('chrome-extension://', '') ===\r\n currentUrl.replace('chrome-extension://', ''));\r\n }\r\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\r\n }\r\n if (!HTTP_REGEX.test(protocol)) {\r\n return false;\r\n }\r\n if (IP_ADDRESS_REGEX.test(expected)) {\r\n // The domain has to be exactly equal to the pattern, as an IP domain will\r\n // only contain the IP, no extra character.\r\n return hostname === expected;\r\n }\r\n // Dots in pattern should be escaped.\r\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\r\n // Non ip address domains.\r\n // domain.com = *.domain.com OR domain.com\r\n const re = new RegExp('^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');\r\n return re.test(hostname);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\r\n/**\r\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\r\n * it will stop working after a retrial. This is a hack to fix this issue.\r\n */\r\nfunction resetUnloadedGapiModules() {\r\n // Clear last failed gapi.load state to force next gapi.load to first\r\n // load the failed gapi.iframes module.\r\n // Get gapix.beacon context.\r\n const beacon = _window().___jsl;\r\n // Get current hint.\r\n if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {\r\n // Get gapi hint.\r\n for (const hint of Object.keys(beacon.H)) {\r\n // Requested modules.\r\n beacon.H[hint].r = beacon.H[hint].r || [];\r\n // Loaded modules.\r\n beacon.H[hint].L = beacon.H[hint].L || [];\r\n // Set requested modules to a copy of the loaded modules.\r\n beacon.H[hint].r = [...beacon.H[hint].L];\r\n // Clear pending callbacks.\r\n if (beacon.CP) {\r\n for (let i = 0; i < beacon.CP.length; i++) {\r\n // Remove all failed pending callbacks.\r\n beacon.CP[i] = null;\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction loadGapi(auth) {\r\n return new Promise((resolve, reject) => {\r\n var _a, _b, _c;\r\n // Function to run when gapi.load is ready.\r\n function loadGapiIframe() {\r\n // The developer may have tried to previously run gapi.load and failed.\r\n // Run this to fix that.\r\n resetUnloadedGapiModules();\r\n gapi.load('gapi.iframes', {\r\n callback: () => {\r\n resolve(gapi.iframes.getContext());\r\n },\r\n ontimeout: () => {\r\n // The above reset may be sufficient, but having this reset after\r\n // failure ensures that if the developer calls gapi.load after the\r\n // connection is re-established and before another attempt to embed\r\n // the iframe, it would work and would not be broken because of our\r\n // failed attempt.\r\n // Timeout when gapi.iframes.Iframe not loaded.\r\n resetUnloadedGapiModules();\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n },\r\n timeout: NETWORK_TIMEOUT.get()\r\n });\r\n }\r\n if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {\r\n // If gapi.iframes.Iframe available, resolve.\r\n resolve(gapi.iframes.getContext());\r\n }\r\n else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {\r\n // Gapi loader ready, load gapi.iframes.\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Create a new iframe callback when this is called so as not to overwrite\r\n // any previous defined callback. This happens if this method is called\r\n // multiple times in parallel and could result in the later callback\r\n // overwriting the previous one. This would end up with a iframe\r\n // timeout.\r\n const cbName = _generateCallbackName('iframefcb');\r\n // GApi loader not available, dynamically load platform.js.\r\n _window()[cbName] = () => {\r\n // GApi loader should be ready.\r\n if (!!gapi.load) {\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Gapi loader failed, throw error.\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }\r\n };\r\n // Load GApi loader.\r\n return _loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)\r\n .catch(e => reject(e));\r\n }\r\n }).catch(error => {\r\n // Reset cached promise to allow for retrial.\r\n cachedGApiLoader = null;\r\n throw error;\r\n });\r\n}\r\nlet cachedGApiLoader = null;\r\nfunction _loadGapi(auth) {\r\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\r\n return cachedGApiLoader;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PING_TIMEOUT = new Delay(5000, 15000);\r\nconst IFRAME_PATH = '__/auth/iframe';\r\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\r\nconst IFRAME_ATTRIBUTES = {\r\n style: {\r\n position: 'absolute',\r\n top: '-100px',\r\n width: '1px',\r\n height: '1px'\r\n },\r\n 'aria-hidden': 'true',\r\n tabindex: '-1'\r\n};\r\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\r\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\r\nconst EID_FROM_APIHOST = new Map([\r\n [\"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */, 'p'],\r\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'],\r\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\r\n]);\r\nfunction getIframeUrl(auth) {\r\n const config = auth.config;\r\n _assert(config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n const url = config.emulator\r\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\r\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\r\n const params = {\r\n apiKey: config.apiKey,\r\n appName: auth.name,\r\n v: SDK_VERSION\r\n };\r\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\r\n if (eid) {\r\n params.eid = eid;\r\n }\r\n const frameworks = auth._getFrameworks();\r\n if (frameworks.length) {\r\n params.fw = frameworks.join(',');\r\n }\r\n return `${url}?${querystring(params).slice(1)}`;\r\n}\r\nasync function _openIframe(auth) {\r\n const context = await _loadGapi(auth);\r\n const gapi = _window().gapi;\r\n _assert(gapi, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return context.open({\r\n where: document.body,\r\n url: getIframeUrl(auth),\r\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\r\n attributes: IFRAME_ATTRIBUTES,\r\n dontclear: true\r\n }, (iframe) => new Promise(async (resolve, reject) => {\r\n await iframe.restyle({\r\n // Prevent iframe from closing on mouse out.\r\n setHideOnLeave: false\r\n });\r\n const networkError = _createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);\r\n // Confirm iframe is correctly loaded.\r\n // To fallback on failure, set a timeout.\r\n const networkErrorTimer = _window().setTimeout(() => {\r\n reject(networkError);\r\n }, PING_TIMEOUT.get());\r\n // Clear timer and resolve pending iframe ready promise.\r\n function clearTimerAndResolve() {\r\n _window().clearTimeout(networkErrorTimer);\r\n resolve(iframe);\r\n }\r\n // This returns an IThenable. However the reject part does not call\r\n // when the iframe is not loaded.\r\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\r\n reject(networkError);\r\n });\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst BASE_POPUP_OPTIONS = {\r\n location: 'yes',\r\n resizable: 'yes',\r\n statusbar: 'yes',\r\n toolbar: 'no'\r\n};\r\nconst DEFAULT_WIDTH = 500;\r\nconst DEFAULT_HEIGHT = 600;\r\nconst TARGET_BLANK = '_blank';\r\nconst FIREFOX_EMPTY_URL = 'http://localhost';\r\nclass AuthPopup {\r\n constructor(window) {\r\n this.window = window;\r\n this.associatedEvent = null;\r\n }\r\n close() {\r\n if (this.window) {\r\n try {\r\n this.window.close();\r\n }\r\n catch (e) { }\r\n }\r\n }\r\n}\r\nfunction _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {\r\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\r\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\r\n let target = '';\r\n const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,\r\n left });\r\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\r\n // specified, even though the popup is not necessarily blocked.\r\n const ua = getUA().toLowerCase();\r\n if (name) {\r\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\r\n }\r\n if (_isFirefox(ua)) {\r\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\r\n url = url || FIREFOX_EMPTY_URL;\r\n // Firefox disables by default scrolling on popup windows, which can create\r\n // issues when the user has many Google accounts, for instance.\r\n options.scrollbars = 'yes';\r\n }\r\n const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');\r\n if (_isIOSStandalone(ua) && target !== '_self') {\r\n openAsNewWindowIOS(url || '', target);\r\n return new AuthPopup(null);\r\n }\r\n // about:blank getting sanitized causing browsers like IE/Edge to display\r\n // brief error message before redirecting to handler.\r\n const newWin = window.open(url || '', target, optionsString);\r\n _assert(newWin, auth, \"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */);\r\n // Flaky on IE edge, encapsulate with a try and catch.\r\n try {\r\n newWin.focus();\r\n }\r\n catch (e) { }\r\n return new AuthPopup(newWin);\r\n}\r\nfunction openAsNewWindowIOS(url, target) {\r\n const el = document.createElement('a');\r\n el.href = url;\r\n el.target = target;\r\n const click = document.createEvent('MouseEvent');\r\n click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);\r\n el.dispatchEvent(click);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * URL for Authentication widget which will initiate the OAuth handshake\r\n *\r\n * @internal\r\n */\r\nconst WIDGET_PATH = '__/auth/handler';\r\n/**\r\n * URL for emulated environment\r\n *\r\n * @internal\r\n */\r\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\r\nfunction _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {\r\n _assert(auth.config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n _assert(auth.config.apiKey, auth, \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */);\r\n const params = {\r\n apiKey: auth.config.apiKey,\r\n appName: auth.name,\r\n authType,\r\n redirectUrl,\r\n v: SDK_VERSION,\r\n eventId\r\n };\r\n if (provider instanceof FederatedAuthProvider) {\r\n provider.setDefaultLanguage(auth.languageCode);\r\n params.providerId = provider.providerId || '';\r\n if (!isEmpty(provider.getCustomParameters())) {\r\n params.customParameters = JSON.stringify(provider.getCustomParameters());\r\n }\r\n // TODO set additionalParams from the provider as well?\r\n for (const [key, value] of Object.entries(additionalParams || {})) {\r\n params[key] = value;\r\n }\r\n }\r\n if (provider instanceof BaseOAuthProvider) {\r\n const scopes = provider.getScopes().filter(scope => scope !== '');\r\n if (scopes.length > 0) {\r\n params.scopes = scopes.join(',');\r\n }\r\n }\r\n if (auth.tenantId) {\r\n params.tid = auth.tenantId;\r\n }\r\n // TODO: maybe set eid as endipointId\r\n // TODO: maybe set fw as Frameworks.join(\",\")\r\n const paramsDict = params;\r\n for (const key of Object.keys(paramsDict)) {\r\n if (paramsDict[key] === undefined) {\r\n delete paramsDict[key];\r\n }\r\n }\r\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}`;\r\n}\r\nfunction getHandlerBase({ config }) {\r\n if (!config.emulator) {\r\n return `https://${config.authDomain}/${WIDGET_PATH}`;\r\n }\r\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The special web storage event\r\n *\r\n */\r\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\r\nclass BrowserPopupRedirectResolver {\r\n constructor() {\r\n this.eventManagers = {};\r\n this.iframes = {};\r\n this.originValidationPromises = {};\r\n this._redirectPersistence = browserSessionPersistence;\r\n this._completeRedirectFn = _getRedirectResult;\r\n this._overrideRedirectResult = _overrideRedirectResult;\r\n }\r\n // Wrapping in async even though we don't await anywhere in order\r\n // to make sure errors are raised as promise rejections\r\n async _openPopup(auth, provider, authType, eventId) {\r\n var _a;\r\n debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');\r\n const url = _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n return _open(auth, url, _generateEventId());\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n await this._originValidation(auth);\r\n _setWindowLocation(_getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId));\r\n return new Promise(() => { });\r\n }\r\n _initialize(auth) {\r\n const key = auth._key();\r\n if (this.eventManagers[key]) {\r\n const { manager, promise } = this.eventManagers[key];\r\n if (manager) {\r\n return Promise.resolve(manager);\r\n }\r\n else {\r\n debugAssert(promise, 'If manager is not set, promise should be');\r\n return promise;\r\n }\r\n }\r\n const promise = this.initAndGetManager(auth);\r\n this.eventManagers[key] = { promise };\r\n // If the promise is rejected, the key should be removed so that the\r\n // operation can be retried later.\r\n promise.catch(() => {\r\n delete this.eventManagers[key];\r\n });\r\n return promise;\r\n }\r\n async initAndGetManager(auth) {\r\n const iframe = await _openIframe(auth);\r\n const manager = new AuthEventManager(auth);\r\n iframe.register('authEvent', (iframeEvent) => {\r\n _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, \"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */);\r\n // TODO: Consider splitting redirect and popup events earlier on\r\n const handled = manager.onEvent(iframeEvent.authEvent);\r\n return { status: handled ? \"ACK\" /* GapiOutcome.ACK */ : \"ERROR\" /* GapiOutcome.ERROR */ };\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n this.eventManagers[auth._key()] = { manager };\r\n this.iframes[auth._key()] = iframe;\r\n return manager;\r\n }\r\n _isIframeWebStorageSupported(auth, cb) {\r\n const iframe = this.iframes[auth._key()];\r\n iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {\r\n var _a;\r\n const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];\r\n if (isSupported !== undefined) {\r\n cb(!!isSupported);\r\n }\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n }\r\n _originValidation(auth) {\r\n const key = auth._key();\r\n if (!this.originValidationPromises[key]) {\r\n this.originValidationPromises[key] = _validateOrigin(auth);\r\n }\r\n return this.originValidationPromises[key];\r\n }\r\n get _shouldInitProactively() {\r\n // Mobile browsers and Safari need to optimistically initialize\r\n return _isMobileBrowser() || _isSafari() || _isIOS();\r\n }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for browser\r\n * based applications.\r\n *\r\n * @public\r\n */\r\nconst browserPopupRedirectResolver = BrowserPopupRedirectResolver;\n\nclass MultiFactorAssertionImpl {\r\n constructor(factorId) {\r\n this.factorId = factorId;\r\n }\r\n _process(auth, session, displayName) {\r\n switch (session.type) {\r\n case \"enroll\" /* MultiFactorSessionType.ENROLL */:\r\n return this._finalizeEnroll(auth, session.credential, displayName);\r\n case \"signin\" /* MultiFactorSessionType.SIGN_IN */:\r\n return this._finalizeSignIn(auth, session.credential);\r\n default:\r\n return debugFail('unexpected MultiFactorSessionType');\r\n }\r\n }\r\n}\n\n/**\r\n * {@inheritdoc PhoneMultiFactorAssertion}\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(credential) {\r\n super(\"phone\" /* FactorId.PHONE */);\r\n this.credential = credential;\r\n }\r\n /** @internal */\r\n static _fromCredential(credential) {\r\n return new PhoneMultiFactorAssertionImpl(credential);\r\n }\r\n /** @internal */\r\n _finalizeEnroll(auth, idToken, displayName) {\r\n return finalizeEnrollPhoneMfa(auth, {\r\n idToken,\r\n displayName,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n /** @internal */\r\n _finalizeSignIn(auth, mfaPendingCredential) {\r\n return finalizeSignInPhoneMfa(auth, {\r\n mfaPendingCredential,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorGenerator {\r\n constructor() { }\r\n /**\r\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\r\n *\r\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\r\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}\r\n */\r\n static assertion(credential) {\r\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\r\n }\r\n}\r\n/**\r\n * The identifier of the phone second factor: `phone`.\r\n */\r\nPhoneMultiFactorGenerator.FACTOR_ID = 'phone';\n\nvar name = \"@firebase/auth\";\nvar version = \"0.21.1\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthInterop {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.internalListeners = new Map();\r\n }\r\n getUid() {\r\n var _a;\r\n this.assertAuthConfigured();\r\n return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;\r\n }\r\n async getToken(forceRefresh) {\r\n this.assertAuthConfigured();\r\n await this.auth._initializationPromise;\r\n if (!this.auth.currentUser) {\r\n return null;\r\n }\r\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\r\n return { accessToken };\r\n }\r\n addAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n if (this.internalListeners.has(listener)) {\r\n return;\r\n }\r\n const unsubscribe = this.auth.onIdTokenChanged(user => {\r\n listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);\r\n });\r\n this.internalListeners.set(listener, unsubscribe);\r\n this.updateProactiveRefresh();\r\n }\r\n removeAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n const unsubscribe = this.internalListeners.get(listener);\r\n if (!unsubscribe) {\r\n return;\r\n }\r\n this.internalListeners.delete(listener);\r\n unsubscribe();\r\n this.updateProactiveRefresh();\r\n }\r\n assertAuthConfigured() {\r\n _assert(this.auth._initializationPromise, \"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);\r\n }\r\n updateProactiveRefresh() {\r\n if (this.internalListeners.size > 0) {\r\n this.auth._startProactiveRefresh();\r\n }\r\n else {\r\n this.auth._stopProactiveRefresh();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getVersionForPlatform(clientPlatform) {\r\n switch (clientPlatform) {\r\n case \"Node\" /* ClientPlatform.NODE */:\r\n return 'node';\r\n case \"ReactNative\" /* ClientPlatform.REACT_NATIVE */:\r\n return 'rn';\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n return 'webworker';\r\n case \"Cordova\" /* ClientPlatform.CORDOVA */:\r\n return 'cordova';\r\n default:\r\n return undefined;\r\n }\r\n}\r\n/** @internal */\r\nfunction registerAuth(clientPlatform) {\r\n _registerComponent(new Component(\"auth\" /* _ComponentName.AUTH */, (container, { options: deps }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const heartbeatServiceProvider = container.getProvider('heartbeat');\r\n const { apiKey, authDomain } = app.options;\r\n return ((app, heartbeatServiceProvider) => {\r\n _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });\r\n // Auth domain is optional if IdP sign in isn't being used\r\n _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, {\r\n appName: app.name\r\n });\r\n const config = {\r\n apiKey,\r\n authDomain,\r\n clientPlatform,\r\n apiHost: \"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */,\r\n tokenApiHost: \"securetoken.googleapis.com\" /* DefaultConfig.TOKEN_API_HOST */,\r\n apiScheme: \"https\" /* DefaultConfig.API_SCHEME */,\r\n sdkClientVersion: _getClientVersion(clientPlatform)\r\n };\r\n const authInstance = new AuthImpl(app, heartbeatServiceProvider, config);\r\n _initializeAuthInstance(authInstance, deps);\r\n return authInstance;\r\n })(app, heartbeatServiceProvider);\r\n }, \"PUBLIC\" /* ComponentType.PUBLIC */)\r\n /**\r\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\r\n * For why we do this, See go/firebase-next-auth-init\r\n */\r\n .setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */)\r\n /**\r\n * Because all firebase products that depend on auth depend on auth-internal directly,\r\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\r\n */\r\n .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {\r\n const authInternalProvider = container.getProvider(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */);\r\n authInternalProvider.initialize();\r\n }));\r\n _registerComponent(new Component(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */, container => {\r\n const auth = _castAuth(container.getProvider(\"auth\" /* _ComponentName.AUTH */).getImmediate());\r\n return (auth => new AuthInterop(auth))(auth);\r\n }, \"PRIVATE\" /* ComponentType.PRIVATE */).setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */));\r\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\r\nconst authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\r\nlet lastPostedIdToken = null;\r\nconst mintCookieFactory = (url) => async (user) => {\r\n const idTokenResult = user && (await user.getIdTokenResult());\r\n const idTokenAge = idTokenResult &&\r\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;\r\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\r\n return;\r\n }\r\n // Specifically trip null => undefined when logged out, to delete any existing cookie\r\n const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;\r\n if (lastPostedIdToken === idToken) {\r\n return;\r\n }\r\n lastPostedIdToken = idToken;\r\n await fetch(url, {\r\n method: idToken ? 'POST' : 'DELETE',\r\n headers: idToken\r\n ? {\r\n 'Authorization': `Bearer ${idToken}`\r\n }\r\n : {}\r\n });\r\n};\r\n/**\r\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\r\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\r\n *\r\n * @param app - The Firebase App.\r\n *\r\n * @public\r\n */\r\nfunction getAuth(app = getApp()) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n return provider.getImmediate();\r\n }\r\n const auth = initializeAuth(app, {\r\n popupRedirectResolver: browserPopupRedirectResolver,\r\n persistence: [\r\n indexedDBLocalPersistence,\r\n browserLocalPersistence,\r\n browserSessionPersistence\r\n ]\r\n });\r\n const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');\r\n if (authTokenSyncUrl) {\r\n const mintCookie = mintCookieFactory(authTokenSyncUrl);\r\n beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));\r\n onIdTokenChanged(auth, user => mintCookie(user));\r\n }\r\n const authEmulatorHost = getDefaultEmulatorHost('auth');\r\n if (authEmulatorHost) {\r\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\r\n }\r\n return auth;\r\n}\r\nregisterAuth(\"Browser\" /* ClientPlatform.BROWSER */);\n\nexport { signInWithCustomToken as $, ActionCodeOperation as A, debugErrorMap as B, prodErrorMap as C, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as D, initializeAuth as E, FactorId as F, connectAuthEmulator as G, AuthCredential as H, EmailAuthCredential as I, OAuthCredential as J, PhoneAuthCredential as K, inMemoryPersistence as L, EmailAuthProvider as M, FacebookAuthProvider as N, OperationType as O, PhoneAuthProvider as P, GoogleAuthProvider as Q, RecaptchaVerifier as R, SignInMethod as S, GithubAuthProvider as T, OAuthProvider as U, SAMLAuthProvider as V, TwitterAuthProvider as W, signInAnonymously as X, signInWithCredential as Y, linkWithCredential as Z, reauthenticateWithCredential as _, browserSessionPersistence as a, sendPasswordResetEmail as a0, confirmPasswordReset as a1, applyActionCode as a2, checkActionCode as a3, verifyPasswordResetCode as a4, createUserWithEmailAndPassword as a5, signInWithEmailAndPassword as a6, sendSignInLinkToEmail as a7, isSignInWithEmailLink as a8, signInWithEmailLink as a9, _persistenceKeyName as aA, _getRedirectResult as aB, _overrideRedirectResult as aC, _clearRedirectOutcomes as aD, _castAuth as aE, UserImpl as aF, AuthImpl as aG, _getClientVersion as aH, _generateEventId as aI, AuthPopup as aJ, FetchProvider as aK, SAMLAuthCredential as aL, fetchSignInMethodsForEmail as aa, sendEmailVerification as ab, verifyBeforeUpdateEmail as ac, ActionCodeURL as ad, parseActionCodeURL as ae, updateProfile as af, updateEmail as ag, updatePassword as ah, getIdToken as ai, getIdTokenResult as aj, unlink as ak, getAdditionalUserInfo as al, reload as am, getMultiFactorResolver as an, multiFactor as ao, debugAssert as ap, _isIOS as aq, _isAndroid as ar, _fail as as, _getRedirectUrl as at, _getProjectConfig as au, _isIOS7Or8 as av, _createError as aw, _assert as ax, AuthEventManager as ay, _getInstance as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, getAuth as n, ProviderId as o, setPersistence as p, onIdTokenChanged as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, beforeAuthStateChanged as t, updatePhoneNumber as u, onAuthStateChanged as v, useDeviceLanguage as w, updateCurrentUser as x, signOut as y, deleteUser as z };\n//# sourceMappingURL=index-e5b3cc81.js.map\n","import { ap as debugAssert, aq as _isIOS, ar as _isAndroid, as as _fail, at as _getRedirectUrl, au as _getProjectConfig, av as _isIOS7Or8, aw as _createError, ax as _assert, ay as AuthEventManager, az as _getInstance, b as browserLocalPersistence, aA as _persistenceKeyName, a as browserSessionPersistence, aB as _getRedirectResult, aC as _overrideRedirectResult, aD as _clearRedirectOutcomes, aE as _castAuth } from './index-e5b3cc81.js';\nexport { A as ActionCodeOperation, ad as ActionCodeURL, H as AuthCredential, D as AuthErrorCodes, aG as AuthImpl, aJ as AuthPopup, I as EmailAuthCredential, M as EmailAuthProvider, N as FacebookAuthProvider, F as FactorId, aK as FetchProvider, T as GithubAuthProvider, Q as GoogleAuthProvider, J as OAuthCredential, U as OAuthProvider, O as OperationType, K as PhoneAuthCredential, P as PhoneAuthProvider, m as PhoneMultiFactorGenerator, o as ProviderId, R as RecaptchaVerifier, aL as SAMLAuthCredential, V as SAMLAuthProvider, S as SignInMethod, W as TwitterAuthProvider, aF as UserImpl, ax as _assert, aE as _castAuth, as as _fail, aI as _generateEventId, aH as _getClientVersion, az as _getInstance, aB as _getRedirectResult, aC as _overrideRedirectResult, aA as _persistenceKeyName, a2 as applyActionCode, t as beforeAuthStateChanged, b as browserLocalPersistence, k as browserPopupRedirectResolver, a as browserSessionPersistence, a3 as checkActionCode, a1 as confirmPasswordReset, G as connectAuthEmulator, a5 as createUserWithEmailAndPassword, B as debugErrorMap, z as deleteUser, aa as fetchSignInMethodsForEmail, al as getAdditionalUserInfo, n as getAuth, ai as getIdToken, aj as getIdTokenResult, an as getMultiFactorResolver, j as getRedirectResult, L as inMemoryPersistence, i as indexedDBLocalPersistence, E as initializeAuth, a8 as isSignInWithEmailLink, Z as linkWithCredential, l as linkWithPhoneNumber, d as linkWithPopup, g as linkWithRedirect, ao as multiFactor, v as onAuthStateChanged, q as onIdTokenChanged, ae as parseActionCodeURL, C as prodErrorMap, _ as reauthenticateWithCredential, r as reauthenticateWithPhoneNumber, e as reauthenticateWithPopup, h as reauthenticateWithRedirect, am as reload, ab as sendEmailVerification, a0 as sendPasswordResetEmail, a7 as sendSignInLinkToEmail, p as setPersistence, X as signInAnonymously, Y as signInWithCredential, $ as signInWithCustomToken, a6 as signInWithEmailAndPassword, a9 as signInWithEmailLink, s as signInWithPhoneNumber, c as signInWithPopup, f as signInWithRedirect, y as signOut, ak as unlink, x as updateCurrentUser, ag as updateEmail, ah as updatePassword, u as updatePhoneNumber, af as updateProfile, w as useDeviceLanguage, ac as verifyBeforeUpdateEmail, a4 as verifyPasswordResetCode } from './index-e5b3cc81.js';\nimport { querystringDecode } from '@firebase/util';\nimport '@firebase/app';\nimport '@firebase/logger';\nimport 'tslib';\nimport '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _cordovaWindow() {\r\n return window;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * How long to wait after the app comes back into focus before concluding that\r\n * the user closed the sign in tab.\r\n */\r\nconst REDIRECT_TIMEOUT_MS = 2000;\r\n/**\r\n * Generates the URL for the OAuth handler.\r\n */\r\nasync function _generateHandlerUrl(auth, event, provider) {\r\n var _a;\r\n // Get the cordova plugins\r\n const { BuildInfo } = _cordovaWindow();\r\n debugAssert(event.sessionId, 'AuthEvent did not contain a session ID');\r\n const sessionDigest = await computeSha256(event.sessionId);\r\n const additionalParams = {};\r\n if (_isIOS()) {\r\n // iOS app identifier\r\n additionalParams['ibi'] = BuildInfo.packageName;\r\n }\r\n else if (_isAndroid()) {\r\n // Android app identifier\r\n additionalParams['apn'] = BuildInfo.packageName;\r\n }\r\n else {\r\n _fail(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n }\r\n // Add the display name if available\r\n if (BuildInfo.displayName) {\r\n additionalParams['appDisplayName'] = BuildInfo.displayName;\r\n }\r\n // Attached the hashed session ID\r\n additionalParams['sessionId'] = sessionDigest;\r\n return _getRedirectUrl(auth, provider, event.type, undefined, (_a = event.eventId) !== null && _a !== void 0 ? _a : undefined, additionalParams);\r\n}\r\n/**\r\n * Validates that this app is valid for this project configuration\r\n */\r\nasync function _validateOrigin(auth) {\r\n const { BuildInfo } = _cordovaWindow();\r\n const request = {};\r\n if (_isIOS()) {\r\n request.iosBundleId = BuildInfo.packageName;\r\n }\r\n else if (_isAndroid()) {\r\n request.androidPackageName = BuildInfo.packageName;\r\n }\r\n else {\r\n _fail(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n }\r\n // Will fail automatically if package name is not authorized\r\n await _getProjectConfig(auth, request);\r\n}\r\nfunction _performRedirect(handlerUrl) {\r\n // Get the cordova plugins\r\n const { cordova } = _cordovaWindow();\r\n return new Promise(resolve => {\r\n cordova.plugins.browsertab.isAvailable(browserTabIsAvailable => {\r\n let iabRef = null;\r\n if (browserTabIsAvailable) {\r\n cordova.plugins.browsertab.openUrl(handlerUrl);\r\n }\r\n else {\r\n // TODO: Return the inappbrowser ref that's returned from the open call\r\n iabRef = cordova.InAppBrowser.open(handlerUrl, _isIOS7Or8() ? '_blank' : '_system', 'location=yes');\r\n }\r\n resolve(iabRef);\r\n });\r\n });\r\n}\r\n/**\r\n * This function waits for app activity to be seen before resolving. It does\r\n * this by attaching listeners to various dom events. Once the app is determined\r\n * to be visible, this promise resolves. AFTER that resolution, the listeners\r\n * are detached and any browser tabs left open will be closed.\r\n */\r\nasync function _waitForAppResume(auth, eventListener, iabRef) {\r\n // Get the cordova plugins\r\n const { cordova } = _cordovaWindow();\r\n let cleanup = () => { };\r\n try {\r\n await new Promise((resolve, reject) => {\r\n let onCloseTimer = null;\r\n // DEFINE ALL THE CALLBACKS =====\r\n function authEventSeen() {\r\n var _a;\r\n // Auth event was detected. Resolve this promise and close the extra\r\n // window if it's still open.\r\n resolve();\r\n const closeBrowserTab = (_a = cordova.plugins.browsertab) === null || _a === void 0 ? void 0 : _a.close;\r\n if (typeof closeBrowserTab === 'function') {\r\n closeBrowserTab();\r\n }\r\n // Close inappbrowser emebedded webview in iOS7 and 8 case if still\r\n // open.\r\n if (typeof (iabRef === null || iabRef === void 0 ? void 0 : iabRef.close) === 'function') {\r\n iabRef.close();\r\n }\r\n }\r\n function resumed() {\r\n if (onCloseTimer) {\r\n // This code already ran; do not rerun.\r\n return;\r\n }\r\n onCloseTimer = window.setTimeout(() => {\r\n // Wait two seeconds after resume then reject.\r\n reject(_createError(auth, \"redirect-cancelled-by-user\" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */));\r\n }, REDIRECT_TIMEOUT_MS);\r\n }\r\n function visibilityChanged() {\r\n if ((document === null || document === void 0 ? void 0 : document.visibilityState) === 'visible') {\r\n resumed();\r\n }\r\n }\r\n // ATTACH ALL THE LISTENERS =====\r\n // Listen for the auth event\r\n eventListener.addPassiveListener(authEventSeen);\r\n // Listen for resume and visibility events\r\n document.addEventListener('resume', resumed, false);\r\n if (_isAndroid()) {\r\n document.addEventListener('visibilitychange', visibilityChanged, false);\r\n }\r\n // SETUP THE CLEANUP FUNCTION =====\r\n cleanup = () => {\r\n eventListener.removePassiveListener(authEventSeen);\r\n document.removeEventListener('resume', resumed, false);\r\n document.removeEventListener('visibilitychange', visibilityChanged, false);\r\n if (onCloseTimer) {\r\n window.clearTimeout(onCloseTimer);\r\n }\r\n };\r\n });\r\n }\r\n finally {\r\n cleanup();\r\n }\r\n}\r\n/**\r\n * Checks the configuration of the Cordova environment. This has no side effect\r\n * if the configuration is correct; otherwise it throws an error with the\r\n * missing plugin.\r\n */\r\nfunction _checkCordovaConfiguration(auth) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\r\n const win = _cordovaWindow();\r\n // Check all dependencies installed.\r\n // https://github.com/nordnet/cordova-universal-links-plugin\r\n // Note that cordova-universal-links-plugin has been abandoned.\r\n // A fork with latest fixes is available at:\r\n // https://www.npmjs.com/package/cordova-universal-links-plugin-fix\r\n _assert(typeof ((_a = win === null || win === void 0 ? void 0 : win.universalLinks) === null || _a === void 0 ? void 0 : _a.subscribe) === 'function', auth, \"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-universal-links-plugin-fix'\r\n });\r\n // https://www.npmjs.com/package/cordova-plugin-buildinfo\r\n _assert(typeof ((_b = win === null || win === void 0 ? void 0 : win.BuildInfo) === null || _b === void 0 ? void 0 : _b.packageName) !== 'undefined', auth, \"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-plugin-buildInfo'\r\n });\r\n // https://github.com/google/cordova-plugin-browsertab\r\n _assert(typeof ((_e = (_d = (_c = win === null || win === void 0 ? void 0 : win.cordova) === null || _c === void 0 ? void 0 : _c.plugins) === null || _d === void 0 ? void 0 : _d.browsertab) === null || _e === void 0 ? void 0 : _e.openUrl) === 'function', auth, \"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-plugin-browsertab'\r\n });\r\n _assert(typeof ((_h = (_g = (_f = win === null || win === void 0 ? void 0 : win.cordova) === null || _f === void 0 ? void 0 : _f.plugins) === null || _g === void 0 ? void 0 : _g.browsertab) === null || _h === void 0 ? void 0 : _h.isAvailable) === 'function', auth, \"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-plugin-browsertab'\r\n });\r\n // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/\r\n _assert(typeof ((_k = (_j = win === null || win === void 0 ? void 0 : win.cordova) === null || _j === void 0 ? void 0 : _j.InAppBrowser) === null || _k === void 0 ? void 0 : _k.open) === 'function', auth, \"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-plugin-inappbrowser'\r\n });\r\n}\r\n/**\r\n * Computes the SHA-256 of a session ID. The SubtleCrypto interface is only\r\n * available in \"secure\" contexts, which covers Cordova (which is served on a file\r\n * protocol).\r\n */\r\nasync function computeSha256(sessionId) {\r\n const bytes = stringToArrayBuffer(sessionId);\r\n // TODO: For IE11 crypto has a different name and this operation comes back\r\n // as an object, not a promise. This is the old proposed standard that\r\n // is used by IE11:\r\n // https://www.w3.org/TR/2013/WD-WebCryptoAPI-20130108/#cryptooperation-interface\r\n const buf = await crypto.subtle.digest('SHA-256', bytes);\r\n const arr = Array.from(new Uint8Array(buf));\r\n return arr.map(num => num.toString(16).padStart(2, '0')).join('');\r\n}\r\nfunction stringToArrayBuffer(str) {\r\n // This function is only meant to deal with an ASCII charset and makes\r\n // certain simplifying assumptions.\r\n debugAssert(/[0-9a-zA-Z]+/.test(str), 'Can only convert alpha-numeric strings');\r\n if (typeof TextEncoder !== 'undefined') {\r\n return new TextEncoder().encode(str);\r\n }\r\n const buff = new ArrayBuffer(str.length);\r\n const view = new Uint8Array(buff);\r\n for (let i = 0; i < str.length; i++) {\r\n view[i] = str.charCodeAt(i);\r\n }\r\n return view;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SESSION_ID_LENGTH = 20;\r\n/** Custom AuthEventManager that adds passive listeners to events */\r\nclass CordovaAuthEventManager extends AuthEventManager {\r\n constructor() {\r\n super(...arguments);\r\n this.passiveListeners = new Set();\r\n this.initPromise = new Promise(resolve => {\r\n this.resolveInialized = resolve;\r\n });\r\n }\r\n addPassiveListener(cb) {\r\n this.passiveListeners.add(cb);\r\n }\r\n removePassiveListener(cb) {\r\n this.passiveListeners.delete(cb);\r\n }\r\n // In a Cordova environment, this manager can live through multiple redirect\r\n // operations\r\n resetRedirect() {\r\n this.queuedRedirectEvent = null;\r\n this.hasHandledPotentialRedirect = false;\r\n }\r\n /** Override the onEvent method */\r\n onEvent(event) {\r\n this.resolveInialized();\r\n this.passiveListeners.forEach(cb => cb(event));\r\n return super.onEvent(event);\r\n }\r\n async initialized() {\r\n await this.initPromise;\r\n }\r\n}\r\n/**\r\n * Generates a (partial) {@link AuthEvent}.\r\n */\r\nfunction _generateNewEvent(auth, type, eventId = null) {\r\n return {\r\n type,\r\n eventId,\r\n urlResponse: null,\r\n sessionId: generateSessionId(),\r\n postBody: null,\r\n tenantId: auth.tenantId,\r\n error: _createError(auth, \"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */)\r\n };\r\n}\r\nfunction _savePartialEvent(auth, event) {\r\n return storage()._set(persistenceKey(auth), event);\r\n}\r\nasync function _getAndRemoveEvent(auth) {\r\n const event = (await storage()._get(persistenceKey(auth)));\r\n if (event) {\r\n await storage()._remove(persistenceKey(auth));\r\n }\r\n return event;\r\n}\r\nfunction _eventFromPartialAndUrl(partialEvent, url) {\r\n var _a, _b;\r\n // Parse the deep link within the dynamic link URL.\r\n const callbackUrl = _getDeepLinkFromCallback(url);\r\n // Confirm it is actually a callback URL.\r\n // Currently the universal link will be of this format:\r\n // https://<AUTH_DOMAIN>/__/auth/callback<OAUTH_RESPONSE>\r\n // This is a fake URL but is not intended to take the user anywhere\r\n // and just redirect to the app.\r\n if (callbackUrl.includes('/__/auth/callback')) {\r\n // Check if there is an error in the URL.\r\n // This mechanism is also used to pass errors back to the app:\r\n // https://<AUTH_DOMAIN>/__/auth/callback?firebaseError=<STRINGIFIED_ERROR>\r\n const params = searchParamsOrEmpty(callbackUrl);\r\n // Get the error object corresponding to the stringified error if found.\r\n const errorObject = params['firebaseError']\r\n ? parseJsonOrNull(decodeURIComponent(params['firebaseError']))\r\n : null;\r\n const code = (_b = (_a = errorObject === null || errorObject === void 0 ? void 0 : errorObject['code']) === null || _a === void 0 ? void 0 : _a.split('auth/')) === null || _b === void 0 ? void 0 : _b[1];\r\n const error = code ? _createError(code) : null;\r\n if (error) {\r\n return {\r\n type: partialEvent.type,\r\n eventId: partialEvent.eventId,\r\n tenantId: partialEvent.tenantId,\r\n error,\r\n urlResponse: null,\r\n sessionId: null,\r\n postBody: null\r\n };\r\n }\r\n else {\r\n return {\r\n type: partialEvent.type,\r\n eventId: partialEvent.eventId,\r\n tenantId: partialEvent.tenantId,\r\n sessionId: partialEvent.sessionId,\r\n urlResponse: callbackUrl,\r\n postBody: null\r\n };\r\n }\r\n }\r\n return null;\r\n}\r\nfunction generateSessionId() {\r\n const chars = [];\r\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n for (let i = 0; i < SESSION_ID_LENGTH; i++) {\r\n const idx = Math.floor(Math.random() * allowedChars.length);\r\n chars.push(allowedChars.charAt(idx));\r\n }\r\n return chars.join('');\r\n}\r\nfunction storage() {\r\n return _getInstance(browserLocalPersistence);\r\n}\r\nfunction persistenceKey(auth) {\r\n return _persistenceKeyName(\"authEvent\" /* KeyName.AUTH_EVENT */, auth.config.apiKey, auth.name);\r\n}\r\nfunction parseJsonOrNull(json) {\r\n try {\r\n return JSON.parse(json);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n}\r\n// Exported for testing\r\nfunction _getDeepLinkFromCallback(url) {\r\n const params = searchParamsOrEmpty(url);\r\n const link = params['link'] ? decodeURIComponent(params['link']) : undefined;\r\n // Double link case (automatic redirect)\r\n const doubleDeepLink = searchParamsOrEmpty(link)['link'];\r\n // iOS custom scheme links.\r\n const iOSDeepLink = params['deep_link_id']\r\n ? decodeURIComponent(params['deep_link_id'])\r\n : undefined;\r\n const iOSDoubleDeepLink = searchParamsOrEmpty(iOSDeepLink)['link'];\r\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * Optimistically tries to get search params from a string, or else returns an\r\n * empty search params object.\r\n */\r\nfunction searchParamsOrEmpty(url) {\r\n if (!(url === null || url === void 0 ? void 0 : url.includes('?'))) {\r\n return {};\r\n }\r\n const [_, ...rest] = url.split('?');\r\n return querystringDecode(rest.join('?'));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * How long to wait for the initial auth event before concluding no\r\n * redirect pending\r\n */\r\nconst INITIAL_EVENT_TIMEOUT_MS = 500;\r\nclass CordovaPopupRedirectResolver {\r\n constructor() {\r\n this._redirectPersistence = browserSessionPersistence;\r\n this._shouldInitProactively = true; // This is lightweight for Cordova\r\n this.eventManagers = new Map();\r\n this.originValidationPromises = {};\r\n this._completeRedirectFn = _getRedirectResult;\r\n this._overrideRedirectResult = _overrideRedirectResult;\r\n }\r\n async _initialize(auth) {\r\n const key = auth._key();\r\n let manager = this.eventManagers.get(key);\r\n if (!manager) {\r\n manager = new CordovaAuthEventManager(auth);\r\n this.eventManagers.set(key, manager);\r\n this.attachCallbackListeners(auth, manager);\r\n }\r\n return manager;\r\n }\r\n _openPopup(auth) {\r\n _fail(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n _checkCordovaConfiguration(auth);\r\n const manager = await this._initialize(auth);\r\n await manager.initialized();\r\n // Reset the persisted redirect states. This does not matter on Web where\r\n // the redirect always blows away application state entirely. On Cordova,\r\n // the app maintains control flow through the redirect.\r\n manager.resetRedirect();\r\n _clearRedirectOutcomes();\r\n await this._originValidation(auth);\r\n const event = _generateNewEvent(auth, authType, eventId);\r\n await _savePartialEvent(auth, event);\r\n const url = await _generateHandlerUrl(auth, event, provider);\r\n const iabRef = await _performRedirect(url);\r\n return _waitForAppResume(auth, manager, iabRef);\r\n }\r\n _isIframeWebStorageSupported(_auth, _cb) {\r\n throw new Error('Method not implemented.');\r\n }\r\n _originValidation(auth) {\r\n const key = auth._key();\r\n if (!this.originValidationPromises[key]) {\r\n this.originValidationPromises[key] = _validateOrigin(auth);\r\n }\r\n return this.originValidationPromises[key];\r\n }\r\n attachCallbackListeners(auth, manager) {\r\n // Get the global plugins\r\n const { universalLinks, handleOpenURL, BuildInfo } = _cordovaWindow();\r\n const noEventTimeout = setTimeout(async () => {\r\n // We didn't see that initial event. Clear any pending object and\r\n // dispatch no event\r\n await _getAndRemoveEvent(auth);\r\n manager.onEvent(generateNoEvent());\r\n }, INITIAL_EVENT_TIMEOUT_MS);\r\n const universalLinksCb = async (eventData) => {\r\n // We have an event so we can clear the no event timeout\r\n clearTimeout(noEventTimeout);\r\n const partialEvent = await _getAndRemoveEvent(auth);\r\n let finalEvent = null;\r\n if (partialEvent && (eventData === null || eventData === void 0 ? void 0 : eventData['url'])) {\r\n finalEvent = _eventFromPartialAndUrl(partialEvent, eventData['url']);\r\n }\r\n // If finalEvent is never filled, trigger with no event\r\n manager.onEvent(finalEvent || generateNoEvent());\r\n };\r\n // Universal links subscriber doesn't exist for iOS, so we need to check\r\n if (typeof universalLinks !== 'undefined' &&\r\n typeof universalLinks.subscribe === 'function') {\r\n universalLinks.subscribe(null, universalLinksCb);\r\n }\r\n // iOS 7 or 8 custom URL schemes.\r\n // This is also the current default behavior for iOS 9+.\r\n // For this to work, cordova-plugin-customurlscheme needs to be installed.\r\n // https://github.com/EddyVerbruggen/Custom-URL-scheme\r\n // Do not overwrite the existing developer's URL handler.\r\n const existingHandleOpenURL = handleOpenURL;\r\n const packagePrefix = `${BuildInfo.packageName.toLowerCase()}://`;\r\n _cordovaWindow().handleOpenURL = async (url) => {\r\n if (url.toLowerCase().startsWith(packagePrefix)) {\r\n // We want this intentionally to float\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n universalLinksCb({ url });\r\n }\r\n // Call the developer's handler if it is present.\r\n if (typeof existingHandleOpenURL === 'function') {\r\n try {\r\n existingHandleOpenURL(url);\r\n }\r\n catch (e) {\r\n // This is a developer error. Don't stop the flow of the SDK.\r\n console.error(e);\r\n }\r\n }\r\n };\r\n }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for Cordova\r\n * based applications.\r\n *\r\n * @public\r\n */\r\nconst cordovaPopupRedirectResolver = CordovaPopupRedirectResolver;\r\nfunction generateNoEvent() {\r\n return {\r\n type: \"unknown\" /* AuthEventType.UNKNOWN */,\r\n eventId: null,\r\n sessionId: null,\r\n urlResponse: null,\r\n postBody: null,\r\n tenantId: null,\r\n error: _createError(\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */)\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.\r\n// It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it out\r\n// of autogenerated documentation pages to reduce accidental misuse.\r\nfunction addFrameworkForLogging(auth, framework) {\r\n _castAuth(auth)._logFramework(framework);\r\n}\n\nexport { addFrameworkForLogging, cordovaPopupRedirectResolver };\n//# sourceMappingURL=internal.js.map\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 * as impl from '@firebase/auth/internal';\nimport {\n getUA,\n isBrowserExtension,\n isReactNative,\n isNode,\n isIE,\n isIndexedDBAvailable\n} from '@firebase/util';\n\ndeclare global {\n interface Document {\n documentMode?: number;\n }\n}\n\nconst CORDOVA_ONDEVICEREADY_TIMEOUT_MS = 1000;\n\nfunction _getCurrentScheme(): string | null {\n return self?.location?.protocol || null;\n}\n\n/**\n * @return {boolean} Whether the current environment is http or https.\n */\nfunction _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\n/**\n * @param {?string=} ua The user agent.\n * @return {boolean} Whether the app is rendered in a mobile iOS or Android\n * Cordova environment.\n */\nexport function _isAndroidOrIosCordovaScheme(ua: string = getUA()): boolean {\n return !!(\n (_getCurrentScheme() === 'file:' ||\n _getCurrentScheme() === 'ionic:' ||\n _getCurrentScheme() === 'capacitor:') &&\n ua.toLowerCase().match(/iphone|ipad|ipod|android/)\n );\n}\n\n/**\n * @return {boolean} Whether the environment is a native environment, where\n * CORS checks do not apply.\n */\nfunction _isNativeEnvironment(): boolean {\n return isReactNative() || isNode();\n}\n\n/**\n * Checks whether the user agent is IE11.\n * @return {boolean} True if it is IE11.\n */\nfunction _isIe11(): boolean {\n return isIE() && document?.documentMode === 11;\n}\n\n/**\n * Checks whether the user agent is Edge.\n * @param {string} userAgent The browser user agent string.\n * @return {boolean} True if it is Edge.\n */\nfunction _isEdge(ua: string = getUA()): boolean {\n return /Edge\\/\\d+/.test(ua);\n}\n\n/**\n * @param {?string=} opt_userAgent The navigator user agent.\n * @return {boolean} Whether local storage is not synchronized between an iframe\n * and a popup of the same domain.\n */\nfunction _isLocalStorageNotSynchronized(ua: string = getUA()): boolean {\n return _isIe11() || _isEdge(ua);\n}\n\n/** @return {boolean} Whether web storage is supported. */\nexport function _isWebStorageSupported(): boolean {\n try {\n const storage = self.localStorage;\n const key = impl._generateEventId();\n if (storage) {\n // setItem will throw an exception if we cannot access WebStorage (e.g.,\n // Safari in private mode).\n storage['setItem'](key, '1');\n storage['removeItem'](key);\n // For browsers where iframe web storage does not synchronize with a popup\n // of the same domain, indexedDB is used for persistent storage. These\n // browsers include IE11 and Edge.\n // Make sure it is supported (IE11 and Edge private mode does not support\n // that).\n if (_isLocalStorageNotSynchronized()) {\n // In such browsers, if indexedDB is not supported, an iframe cannot be\n // notified of the popup sign in result.\n return isIndexedDBAvailable();\n }\n return true;\n }\n } catch (e) {\n // localStorage is not available from a worker. Test availability of\n // indexedDB.\n return _isWorker() && isIndexedDBAvailable();\n }\n return false;\n}\n\n/**\n * @param {?Object=} global The optional global scope.\n * @return {boolean} Whether current environment is a worker.\n */\nexport function _isWorker(): boolean {\n // WorkerGlobalScope only defined in worker environment.\n return (\n typeof global !== 'undefined' &&\n 'WorkerGlobalScope' in global &&\n 'importScripts' in global\n );\n}\n\nexport function _isPopupRedirectSupported(): boolean {\n return (\n (_isHttpOrHttps() ||\n isBrowserExtension() ||\n _isAndroidOrIosCordovaScheme()) &&\n // React Native with remote debugging reports its location.protocol as\n // http.\n !_isNativeEnvironment() &&\n // Local storage has to be supported for browser popup and redirect\n // operations to work.\n _isWebStorageSupported() &&\n // DOM, popups and redirects are not supported within a worker.\n !_isWorker()\n );\n}\n\n/** Quick check that indicates the platform *may* be Cordova */\nexport function _isLikelyCordova(): boolean {\n return _isAndroidOrIosCordovaScheme() && typeof document !== 'undefined';\n}\n\nexport async function _isCordova(): Promise<boolean> {\n if (!_isLikelyCordova()) {\n return false;\n }\n\n return new Promise(resolve => {\n const timeoutId = setTimeout(() => {\n // We've waited long enough; the telltale Cordova event didn't happen\n resolve(false);\n }, CORDOVA_ONDEVICEREADY_TIMEOUT_MS);\n\n document.addEventListener('deviceready', () => {\n clearTimeout(timeoutId);\n resolve(true);\n });\n });\n}\n\nexport function _getSelfWindow(): Window | null {\n return typeof window !== 'undefined' ? window : null;\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 * as exp from '@firebase/auth/internal';\nimport { isIndexedDBAvailable, isNode, isReactNative } from '@firebase/util';\nimport { _getSelfWindow, _isWebStorageSupported, _isWorker } from './platform';\n\nexport const Persistence = {\n LOCAL: 'local',\n NONE: 'none',\n SESSION: 'session'\n};\n\nconst _assert: typeof exp._assert = exp._assert;\n\nconst PERSISTENCE_KEY = 'persistence';\n\n/**\n * Validates that an argument is a valid persistence value. If an invalid type\n * is specified, an error is thrown synchronously.\n */\nexport function _validatePersistenceArgument(\n auth: exp.Auth,\n persistence: string\n): void {\n _assert(\n Object.values(Persistence).includes(persistence),\n auth,\n exp.AuthErrorCode.INVALID_PERSISTENCE\n );\n // Validate if the specified type is supported in the current environment.\n if (isReactNative()) {\n // This is only supported in a browser.\n _assert(\n persistence !== Persistence.SESSION,\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n if (isNode()) {\n // Only none is supported in Node.js.\n _assert(\n persistence === Persistence.NONE,\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n if (_isWorker()) {\n // In a worker environment, either LOCAL or NONE are supported.\n // If indexedDB not supported and LOCAL provided, throw an error\n _assert(\n persistence === Persistence.NONE ||\n (persistence === Persistence.LOCAL && isIndexedDBAvailable()),\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n // This is restricted by what the browser supports.\n _assert(\n persistence === Persistence.NONE || _isWebStorageSupported(),\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n}\n\nexport async function _savePersistenceForRedirect(\n auth: exp.AuthInternal\n): Promise<void> {\n await auth._initializationPromise;\n const session = getSessionStorageIfAvailable();\n const key = exp._persistenceKeyName(\n PERSISTENCE_KEY,\n auth.config.apiKey,\n auth.name\n );\n if (session) {\n session.setItem(key, auth._getPersistence());\n }\n}\n\nexport function _getPersistencesFromRedirect(\n apiKey: string,\n appName: string\n): exp.Persistence[] {\n const session = getSessionStorageIfAvailable();\n if (!session) {\n return [];\n }\n\n const key = exp._persistenceKeyName(PERSISTENCE_KEY, apiKey, appName);\n const persistence = session.getItem(key);\n\n switch (persistence) {\n case Persistence.NONE:\n return [exp.inMemoryPersistence];\n case Persistence.LOCAL:\n return [exp.indexedDBLocalPersistence, exp.browserSessionPersistence];\n case Persistence.SESSION:\n return [exp.browserSessionPersistence];\n default:\n return [];\n }\n}\n\n/** Returns session storage, or null if the property access errors */\nfunction getSessionStorageIfAvailable(): Storage | null {\n try {\n return _getSelfWindow()?.sessionStorage || null;\n } catch (e) {\n return null;\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 * as exp from '@firebase/auth/internal';\nimport { _isCordova, _isLikelyCordova } from './platform';\n\nconst _assert: typeof exp._assert = exp._assert;\n\n/** Platform-agnostic popup-redirect resolver */\nexport class CompatPopupRedirectResolver\n implements exp.PopupRedirectResolverInternal\n{\n // Create both resolvers for dynamic resolution later\n private readonly browserResolver: exp.PopupRedirectResolverInternal =\n exp._getInstance(exp.browserPopupRedirectResolver);\n private readonly cordovaResolver: exp.PopupRedirectResolverInternal =\n exp._getInstance(exp.cordovaPopupRedirectResolver);\n // The actual resolver in use: either browserResolver or cordovaResolver.\n private underlyingResolver: exp.PopupRedirectResolverInternal | null = null;\n _redirectPersistence = exp.browserSessionPersistence;\n\n _completeRedirectFn: (\n auth: exp.Auth,\n resolver: exp.PopupRedirectResolver,\n bypassAuthState: boolean\n ) => Promise<exp.UserCredential | null> = exp._getRedirectResult;\n _overrideRedirectResult = exp._overrideRedirectResult;\n\n async _initialize(auth: exp.AuthImpl): Promise<exp.EventManager> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._initialize(auth);\n }\n\n async _openPopup(\n auth: exp.AuthImpl,\n provider: exp.AuthProvider,\n authType: exp.AuthEventType,\n eventId?: string\n ): Promise<exp.AuthPopup> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._openPopup(\n auth,\n provider,\n authType,\n eventId\n );\n }\n\n async _openRedirect(\n auth: exp.AuthImpl,\n provider: exp.AuthProvider,\n authType: exp.AuthEventType,\n eventId?: string\n ): Promise<void> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._openRedirect(\n auth,\n provider,\n authType,\n eventId\n );\n }\n\n _isIframeWebStorageSupported(\n auth: exp.AuthImpl,\n cb: (support: boolean) => unknown\n ): void {\n this.assertedUnderlyingResolver._isIframeWebStorageSupported(auth, cb);\n }\n\n _originValidation(auth: exp.Auth): Promise<void> {\n return this.assertedUnderlyingResolver._originValidation(auth);\n }\n\n get _shouldInitProactively(): boolean {\n return _isLikelyCordova() || this.browserResolver._shouldInitProactively;\n }\n\n private get assertedUnderlyingResolver(): exp.PopupRedirectResolverInternal {\n _assert(this.underlyingResolver, exp.AuthErrorCode.INTERNAL_ERROR);\n return this.underlyingResolver;\n }\n\n private async selectUnderlyingResolver(): Promise<void> {\n if (this.underlyingResolver) {\n return;\n }\n\n // We haven't yet determined whether or not we're in Cordova; go ahead\n // and determine that state now.\n const isCordova = await _isCordova();\n this.underlyingResolver = isCordova\n ? this.cordovaResolver\n : this.browserResolver;\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\n/** Forward direction wrapper from Compat --unwrap-> Exp */\nexport interface Wrapper<T> {\n unwrap(): T;\n}\n\n/** Reverse direction wrapper from Exp --wrapped--> Compat */\nexport interface ReverseWrapper<T> {\n wrapped(): T;\n}\n\nexport function unwrap<T>(object: unknown): T {\n return (object as Wrapper<T>).unwrap();\n}\n\nexport function wrapped<T>(object: unknown): T {\n return (object as ReverseWrapper<T>).wrapped();\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 * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { FirebaseError } from '@firebase/util';\nimport { Auth } from './auth';\nimport { User } from './user';\nimport { unwrap, wrapped } from './wrap';\n\nfunction credentialFromResponse(\n userCredential: exp.UserCredentialInternal\n): exp.AuthCredential | null {\n return credentialFromObject(userCredential);\n}\n\nfunction attachExtraErrorFields(auth: exp.Auth, e: FirebaseError): void {\n // The response contains all fields from the server which may or may not\n // actually match the underlying type\n const response = (e.customData as exp.TaggedWithTokenResponse | undefined)\n ?._tokenResponse as unknown as Record<string, string>;\n if ((e as FirebaseError)?.code === 'auth/multi-factor-auth-required') {\n const mfaErr = e as compat.MultiFactorError;\n mfaErr.resolver = new MultiFactorResolver(\n auth,\n exp.getMultiFactorResolver(auth, e as exp.MultiFactorError)\n );\n } else if (response) {\n const credential = credentialFromObject(e);\n const credErr = e as compat.AuthError;\n if (credential) {\n credErr.credential = credential;\n credErr.tenantId = response.tenantId || undefined;\n credErr.email = response.email || undefined;\n credErr.phoneNumber = response.phoneNumber || undefined;\n }\n }\n}\n\nfunction credentialFromObject(\n object: FirebaseError | exp.UserCredential\n): exp.AuthCredential | null {\n const { _tokenResponse } = (\n object instanceof FirebaseError ? object.customData : object\n ) as exp.TaggedWithTokenResponse;\n if (!_tokenResponse) {\n return null;\n }\n\n // Handle phone Auth credential responses, as they have a different format\n // from other backend responses (i.e. no providerId). This is also only the\n // case for user credentials (does not work for errors).\n if (!(object instanceof FirebaseError)) {\n if ('temporaryProof' in _tokenResponse && 'phoneNumber' in _tokenResponse) {\n return exp.PhoneAuthProvider.credentialFromResult(object);\n }\n }\n\n const providerId = _tokenResponse.providerId;\n\n // Email and password is not supported as there is no situation where the\n // server would return the password to the client.\n if (!providerId || providerId === exp.ProviderId.PASSWORD) {\n return null;\n }\n\n let provider: Pick<\n typeof exp.OAuthProvider,\n 'credentialFromResult' | 'credentialFromError'\n >;\n switch (providerId) {\n case exp.ProviderId.GOOGLE:\n provider = exp.GoogleAuthProvider;\n break;\n case exp.ProviderId.FACEBOOK:\n provider = exp.FacebookAuthProvider;\n break;\n case exp.ProviderId.GITHUB:\n provider = exp.GithubAuthProvider;\n break;\n case exp.ProviderId.TWITTER:\n provider = exp.TwitterAuthProvider;\n break;\n default:\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce\n } = _tokenResponse as exp.SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n // TODO(avolkovi): uncomment this and get it working with SAML & OIDC\n if (pendingToken) {\n if (providerId.startsWith('saml.')) {\n return exp.SAMLAuthCredential._create(providerId, pendingToken);\n } else {\n // OIDC and non-default providers excluding Twitter.\n return exp.OAuthCredential._fromParams({\n providerId,\n signInMethod: providerId,\n pendingToken,\n idToken: oauthIdToken,\n accessToken: oauthAccessToken\n });\n }\n }\n return new exp.OAuthProvider(providerId).credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n rawNonce: nonce\n });\n }\n\n return object instanceof FirebaseError\n ? provider.credentialFromError(object)\n : provider.credentialFromResult(object);\n}\n\nexport function convertCredential(\n auth: exp.Auth,\n credentialPromise: Promise<exp.UserCredential>\n): Promise<compat.UserCredential> {\n return credentialPromise\n .catch(e => {\n if (e instanceof FirebaseError) {\n attachExtraErrorFields(auth, e);\n }\n throw e;\n })\n .then(credential => {\n const operationType = credential.operationType;\n const user = credential.user;\n\n return {\n operationType,\n credential: credentialFromResponse(\n credential as exp.UserCredentialInternal\n ),\n additionalUserInfo: exp.getAdditionalUserInfo(\n credential as exp.UserCredential\n ),\n user: User.getOrCreate(user)\n };\n });\n}\n\nexport async function convertConfirmationResult(\n auth: exp.Auth,\n confirmationResultPromise: Promise<exp.ConfirmationResult>\n): Promise<compat.ConfirmationResult> {\n const confirmationResultExp = await confirmationResultPromise;\n return {\n verificationId: confirmationResultExp.verificationId,\n confirm: (verificationCode: string) =>\n convertCredential(auth, confirmationResultExp.confirm(verificationCode))\n };\n}\n\nclass MultiFactorResolver implements compat.MultiFactorResolver {\n readonly auth: Auth;\n constructor(\n auth: exp.Auth,\n private readonly resolver: exp.MultiFactorResolver\n ) {\n this.auth = wrapped(auth);\n }\n\n get session(): compat.MultiFactorSession {\n return this.resolver.session;\n }\n\n get hints(): compat.MultiFactorInfo[] {\n return this.resolver.hints;\n }\n\n resolveSignIn(\n assertion: compat.MultiFactorAssertion\n ): Promise<compat.UserCredential> {\n return convertCredential(\n unwrap(this.auth),\n this.resolver.resolveSignIn(assertion as exp.MultiFactorAssertion)\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 * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Compat } from '@firebase/util';\nimport { _savePersistenceForRedirect } from './persistence';\nimport { CompatPopupRedirectResolver } from './popup_redirect';\nimport {\n convertConfirmationResult,\n convertCredential\n} from './user_credential';\n\nexport class User implements compat.User, Compat<exp.User> {\n // Maintain a map so that there's always a 1:1 mapping between new User and\n // legacy compat users\n private static readonly USER_MAP = new WeakMap<exp.User, User>();\n\n readonly multiFactor: compat.MultiFactorUser;\n\n private constructor(readonly _delegate: exp.User) {\n this.multiFactor = exp.multiFactor(_delegate);\n }\n\n static getOrCreate(user: exp.User): User {\n if (!User.USER_MAP.has(user)) {\n User.USER_MAP.set(user, new User(user));\n }\n\n return User.USER_MAP.get(user)!;\n }\n\n delete(): Promise<void> {\n return this._delegate.delete();\n }\n reload(): Promise<void> {\n return this._delegate.reload();\n }\n toJSON(): object {\n return this._delegate.toJSON();\n }\n getIdTokenResult(forceRefresh?: boolean): Promise<compat.IdTokenResult> {\n return this._delegate.getIdTokenResult(forceRefresh);\n }\n getIdToken(forceRefresh?: boolean): Promise<string> {\n return this._delegate.getIdToken(forceRefresh);\n }\n linkAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.linkWithCredential(credential);\n }\n async linkWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.linkWithCredential(this._delegate, credential as exp.AuthCredential)\n );\n }\n async linkWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this.auth,\n exp.linkWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier)\n );\n }\n async linkWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.linkWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async linkWithRedirect(provider: compat.AuthProvider): Promise<void> {\n await _savePersistenceForRedirect(exp._castAuth(this.auth));\n return exp.linkWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n reauthenticateAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.reauthenticateWithCredential(credential);\n }\n async reauthenticateWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth as unknown as exp.Auth,\n exp.reauthenticateWithCredential(\n this._delegate,\n credential as exp.AuthCredential\n )\n );\n }\n reauthenticateWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this.auth,\n exp.reauthenticateWithPhoneNumber(\n this._delegate,\n phoneNumber,\n applicationVerifier\n )\n );\n }\n reauthenticateWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.reauthenticateWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async reauthenticateWithRedirect(\n provider: compat.AuthProvider\n ): Promise<void> {\n await _savePersistenceForRedirect(exp._castAuth(this.auth));\n return exp.reauthenticateWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n sendEmailVerification(\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.sendEmailVerification(this._delegate, actionCodeSettings);\n }\n async unlink(providerId: string): Promise<compat.User> {\n await exp.unlink(this._delegate, providerId);\n return this;\n }\n updateEmail(newEmail: string): Promise<void> {\n return exp.updateEmail(this._delegate, newEmail);\n }\n updatePassword(newPassword: string): Promise<void> {\n return exp.updatePassword(this._delegate, newPassword);\n }\n updatePhoneNumber(phoneCredential: compat.AuthCredential): Promise<void> {\n return exp.updatePhoneNumber(\n this._delegate,\n phoneCredential as exp.PhoneAuthCredential\n );\n }\n updateProfile(profile: {\n displayName?: string | null;\n photoURL?: string | null;\n }): Promise<void> {\n return exp.updateProfile(this._delegate, profile);\n }\n verifyBeforeUpdateEmail(\n newEmail: string,\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.verifyBeforeUpdateEmail(\n this._delegate,\n newEmail,\n actionCodeSettings\n );\n }\n get emailVerified(): boolean {\n return this._delegate.emailVerified;\n }\n get isAnonymous(): boolean {\n return this._delegate.isAnonymous;\n }\n get metadata(): compat.UserMetadata {\n return this._delegate.metadata;\n }\n get phoneNumber(): string | null {\n return this._delegate.phoneNumber;\n }\n get providerData(): Array<compat.UserInfo | null> {\n return this._delegate.providerData;\n }\n get refreshToken(): string {\n return this._delegate.refreshToken;\n }\n get tenantId(): string | null {\n return this._delegate.tenantId;\n }\n get displayName(): string | null {\n return this._delegate.displayName;\n }\n get email(): string | null {\n return this._delegate.email;\n }\n get photoURL(): string | null {\n return this._delegate.photoURL;\n }\n get providerId(): string {\n return this._delegate.providerId;\n }\n get uid(): string {\n return this._delegate.uid;\n }\n private get auth(): exp.Auth {\n return (this._delegate as exp.UserImpl).auth as unknown as exp.Auth;\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, _FirebaseService } from '@firebase/app-compat';\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Provider } from '@firebase/component';\nimport { ErrorFn, Observer, Unsubscribe } from '@firebase/util';\n\nimport {\n _validatePersistenceArgument,\n Persistence,\n _getPersistencesFromRedirect,\n _savePersistenceForRedirect\n} from './persistence';\nimport { _isPopupRedirectSupported } from './platform';\nimport { CompatPopupRedirectResolver } from './popup_redirect';\nimport { User } from './user';\nimport {\n convertConfirmationResult,\n convertCredential\n} from './user_credential';\nimport { ReverseWrapper, Wrapper } from './wrap';\n\nconst _assert: typeof exp._assert = exp._assert;\n\nexport class Auth\n implements compat.FirebaseAuth, Wrapper<exp.Auth>, _FirebaseService\n{\n static Persistence = Persistence;\n readonly _delegate: exp.AuthImpl;\n\n constructor(readonly app: FirebaseApp, provider: Provider<'auth'>) {\n if (provider.isInitialized()) {\n this._delegate = provider.getImmediate() as exp.AuthImpl;\n this.linkUnderlyingAuth();\n return;\n }\n\n const { apiKey } = app.options;\n // TODO: platform needs to be determined using heuristics\n _assert(apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n\n // TODO: platform needs to be determined using heuristics\n _assert(apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n\n // Only use a popup/redirect resolver in browser environments\n const resolver =\n typeof window !== 'undefined' ? CompatPopupRedirectResolver : undefined;\n this._delegate = provider.initialize({\n options: {\n persistence: buildPersistenceHierarchy(apiKey, app.name),\n popupRedirectResolver: resolver\n }\n }) as exp.AuthImpl;\n\n this._delegate._updateErrorMap(exp.debugErrorMap);\n this.linkUnderlyingAuth();\n }\n\n get emulatorConfig(): compat.EmulatorConfig | null {\n return this._delegate.emulatorConfig;\n }\n\n get currentUser(): compat.User | null {\n if (!this._delegate.currentUser) {\n return null;\n }\n\n return User.getOrCreate(this._delegate.currentUser);\n }\n get languageCode(): string | null {\n return this._delegate.languageCode;\n }\n set languageCode(languageCode: string | null) {\n this._delegate.languageCode = languageCode;\n }\n get settings(): compat.AuthSettings {\n return this._delegate.settings;\n }\n get tenantId(): string | null {\n return this._delegate.tenantId;\n }\n set tenantId(tid: string | null) {\n this._delegate.tenantId = tid;\n }\n useDeviceLanguage(): void {\n this._delegate.useDeviceLanguage();\n }\n signOut(): Promise<void> {\n return this._delegate.signOut();\n }\n useEmulator(url: string, options?: { disableWarnings: boolean }): void {\n exp.connectAuthEmulator(this._delegate, url, options);\n }\n applyActionCode(code: string): Promise<void> {\n return exp.applyActionCode(this._delegate, code);\n }\n\n checkActionCode(code: string): Promise<compat.ActionCodeInfo> {\n return exp.checkActionCode(this._delegate, code);\n }\n\n confirmPasswordReset(code: string, newPassword: string): Promise<void> {\n return exp.confirmPasswordReset(this._delegate, code, newPassword);\n }\n\n async createUserWithEmailAndPassword(\n email: string,\n password: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.createUserWithEmailAndPassword(this._delegate, email, password)\n );\n }\n fetchProvidersForEmail(email: string): Promise<string[]> {\n return this.fetchSignInMethodsForEmail(email);\n }\n fetchSignInMethodsForEmail(email: string): Promise<string[]> {\n return exp.fetchSignInMethodsForEmail(this._delegate, email);\n }\n isSignInWithEmailLink(emailLink: string): boolean {\n return exp.isSignInWithEmailLink(this._delegate, emailLink);\n }\n async getRedirectResult(): Promise<compat.UserCredential> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const credential = await exp.getRedirectResult(\n this._delegate,\n CompatPopupRedirectResolver\n );\n if (!credential) {\n return {\n credential: null,\n user: null\n };\n }\n return convertCredential(this._delegate, Promise.resolve(credential));\n }\n\n // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.\n // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it\n // out of autogenerated documentation pages to reduce accidental misuse.\n addFrameworkForLogging(framework: string): void {\n exp.addFrameworkForLogging(this._delegate, framework);\n }\n\n onAuthStateChanged(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n errorFn?: (error: compat.Error) => unknown,\n completed?: Unsubscribe\n ): Unsubscribe {\n const { next, error, complete } = wrapObservers(\n nextOrObserver,\n errorFn,\n completed\n );\n return this._delegate.onAuthStateChanged(next!, error, complete);\n }\n onIdTokenChanged(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n errorFn?: (error: compat.Error) => unknown,\n completed?: Unsubscribe\n ): Unsubscribe {\n const { next, error, complete } = wrapObservers(\n nextOrObserver,\n errorFn,\n completed\n );\n return this._delegate.onIdTokenChanged(next!, error, complete);\n }\n sendSignInLinkToEmail(\n email: string,\n actionCodeSettings: compat.ActionCodeSettings\n ): Promise<void> {\n return exp.sendSignInLinkToEmail(this._delegate, email, actionCodeSettings);\n }\n sendPasswordResetEmail(\n email: string,\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.sendPasswordResetEmail(\n this._delegate,\n email,\n actionCodeSettings || undefined\n );\n }\n async setPersistence(persistence: string): Promise<void> {\n _validatePersistenceArgument(this._delegate, persistence);\n let converted;\n switch (persistence) {\n case Persistence.SESSION:\n converted = exp.browserSessionPersistence;\n break;\n case Persistence.LOCAL:\n // Not using isIndexedDBAvailable() since it only checks if indexedDB is defined.\n const isIndexedDBFullySupported = await exp\n ._getInstance<exp.PersistenceInternal>(exp.indexedDBLocalPersistence)\n ._isAvailable();\n converted = isIndexedDBFullySupported\n ? exp.indexedDBLocalPersistence\n : exp.browserLocalPersistence;\n break;\n case Persistence.NONE:\n converted = exp.inMemoryPersistence;\n break;\n default:\n return exp._fail(exp.AuthErrorCode.ARGUMENT_ERROR, {\n appName: this._delegate.name\n });\n }\n\n return this._delegate.setPersistence(converted);\n }\n\n signInAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.signInWithCredential(credential);\n }\n signInAnonymously(): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInAnonymously(this._delegate)\n );\n }\n signInWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithCredential(this._delegate, credential as exp.AuthCredential)\n );\n }\n signInWithCustomToken(token: string): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithCustomToken(this._delegate, token)\n );\n }\n signInWithEmailAndPassword(\n email: string,\n password: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithEmailAndPassword(this._delegate, email, password)\n );\n }\n signInWithEmailLink(\n email: string,\n emailLink?: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithEmailLink(this._delegate, email, emailLink)\n );\n }\n signInWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this._delegate,\n exp.signInWithPhoneNumber(\n this._delegate,\n phoneNumber,\n applicationVerifier\n )\n );\n }\n async signInWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n return convertCredential(\n this._delegate,\n exp.signInWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async signInWithRedirect(provider: compat.AuthProvider): Promise<void> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n\n await _savePersistenceForRedirect(this._delegate);\n return exp.signInWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n updateCurrentUser(user: compat.User | null): Promise<void> {\n // remove ts-ignore once overloads are defined for exp functions to accept compat objects\n // @ts-ignore\n return this._delegate.updateCurrentUser(user);\n }\n verifyPasswordResetCode(code: string): Promise<string> {\n return exp.verifyPasswordResetCode(this._delegate, code);\n }\n unwrap(): exp.Auth {\n return this._delegate;\n }\n _delete(): Promise<void> {\n return this._delegate._delete();\n }\n private linkUnderlyingAuth(): void {\n (this._delegate as unknown as ReverseWrapper<Auth>).wrapped = () => this;\n }\n}\n\nfunction wrapObservers(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n error?: (error: compat.Error) => unknown,\n complete?: Unsubscribe\n): Partial<Observer<exp.User | null>> {\n let next = nextOrObserver;\n if (typeof nextOrObserver !== 'function') {\n ({ next, error, complete } = nextOrObserver);\n }\n\n // We know 'next' is now a function\n const oldNext = next as (a: compat.User | null) => unknown;\n\n const newNext = (user: exp.User | null): unknown =>\n oldNext(user && User.getOrCreate(user as exp.User));\n return {\n next: newNext,\n error: error as ErrorFn,\n complete\n };\n}\n\nfunction buildPersistenceHierarchy(\n apiKey: string,\n appName: string\n): exp.Persistence[] {\n // Note this is slightly different behavior: in this case, the stored\n // persistence is checked *first* rather than last. This is because we want\n // to prefer stored persistence type in the hierarchy. This is an empty\n // array if window is not available or there is no pending redirect\n const persistences = _getPersistencesFromRedirect(apiKey, appName);\n\n // If \"self\" is available, add indexedDB\n if (\n typeof self !== 'undefined' &&\n !persistences.includes(exp.indexedDBLocalPersistence)\n ) {\n persistences.push(exp.indexedDBLocalPersistence);\n }\n\n // If \"window\" is available, add HTML Storage persistences\n if (typeof window !== 'undefined') {\n for (const persistence of [\n exp.browserLocalPersistence,\n exp.browserSessionPersistence\n ]) {\n if (!persistences.includes(persistence)) {\n persistences.push(persistence);\n }\n }\n }\n\n // Add in-memory as a final fallback\n if (!persistences.includes(exp.inMemoryPersistence)) {\n persistences.push(exp.inMemoryPersistence);\n }\n\n return persistences;\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 * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport firebase from '@firebase/app-compat';\nimport { Compat } from '@firebase/util';\nimport { unwrap } from './wrap';\n\nexport class PhoneAuthProvider\n implements compat.PhoneAuthProvider, Compat<exp.PhoneAuthProvider>\n{\n providerId = 'phone';\n readonly _delegate: exp.PhoneAuthProvider;\n\n static PHONE_SIGN_IN_METHOD = exp.PhoneAuthProvider.PHONE_SIGN_IN_METHOD;\n static PROVIDER_ID = exp.PhoneAuthProvider.PROVIDER_ID;\n\n static credential(\n verificationId: string,\n verificationCode: string\n ): compat.AuthCredential {\n return exp.PhoneAuthProvider.credential(verificationId, verificationCode);\n }\n\n constructor() {\n // TODO: remove ts-ignore when moving types from auth-types to auth-compat\n // @ts-ignore\n this._delegate = new exp.PhoneAuthProvider(unwrap(firebase.auth!()));\n }\n\n verifyPhoneNumber(\n phoneInfoOptions:\n | string\n | compat.PhoneSingleFactorInfoOptions\n | compat.PhoneMultiFactorEnrollInfoOptions\n | compat.PhoneMultiFactorSignInInfoOptions,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<string> {\n return this._delegate.verifyPhoneNumber(\n // The implementation matches but the types are subtly incompatible\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n phoneInfoOptions as any,\n applicationVerifier\n );\n }\n\n unwrap(): exp.PhoneAuthProvider {\n return this._delegate;\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 firebase, { FirebaseApp } from '@firebase/app-compat';\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Compat } from '@firebase/util';\n\nconst _assert: typeof exp._assert = exp._assert;\n\nexport class RecaptchaVerifier\n implements compat.RecaptchaVerifier, Compat<exp.ApplicationVerifier>\n{\n readonly _delegate: exp.RecaptchaVerifier;\n type: string;\n constructor(\n container: HTMLElement | string,\n parameters?: object | null,\n app: FirebaseApp = firebase.app()\n ) {\n // API key is required for web client RPC calls.\n _assert(app.options?.apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n this._delegate = new exp.RecaptchaVerifier(\n container,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parameters as any,\n\n // TODO: remove ts-ignore when moving types from auth-types to auth-compat\n // @ts-ignore\n app.auth!()\n );\n this.type = this._delegate.type;\n }\n clear(): void {\n this._delegate.clear();\n }\n render(): Promise<number> {\n return this._delegate.render();\n }\n verify(): Promise<string> {\n return this._delegate.verify();\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\n/* eslint-disable camelcase */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport * as impl from '@firebase/auth/internal';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\nimport { FirebaseError } from '@firebase/util';\n\nimport * as types from '@firebase/auth-types';\nimport { name, version } from './package.json';\nimport { Auth } from './src/auth';\nimport { PhoneAuthProvider as CompatAuthProvider } from './src/phone_auth_provider';\nimport { RecaptchaVerifier as CompatRecaptchaVerifier } from './src/recaptcha_verifier';\n\nconst AUTH_TYPE = 'auth-compat';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'auth-compat': types.FirebaseAuth;\n }\n}\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n auth: {\n (app?: FirebaseApp): types.FirebaseAuth;\n Auth: typeof types.FirebaseAuth;\n EmailAuthProvider: typeof types.EmailAuthProvider;\n EmailAuthProvider_Instance: typeof types.EmailAuthProvider_Instance;\n FacebookAuthProvider: typeof types.FacebookAuthProvider;\n FacebookAuthProvider_Instance: typeof types.FacebookAuthProvider_Instance;\n GithubAuthProvider: typeof types.GithubAuthProvider;\n GithubAuthProvider_Instance: typeof types.GithubAuthProvider_Instance;\n GoogleAuthProvider: typeof types.GoogleAuthProvider;\n GoogleAuthProvider_Instance: typeof types.GoogleAuthProvider_Instance;\n OAuthProvider: typeof types.OAuthProvider;\n SAMLAuthProvider: typeof types.SAMLAuthProvider;\n PhoneAuthProvider: typeof types.PhoneAuthProvider;\n PhoneAuthProvider_Instance: typeof types.PhoneAuthProvider_Instance;\n PhoneMultiFactorGenerator: typeof types.PhoneMultiFactorGenerator;\n RecaptchaVerifier: typeof types.RecaptchaVerifier;\n RecaptchaVerifier_Instance: typeof types.RecaptchaVerifier_Instance;\n TwitterAuthProvider: typeof types.TwitterAuthProvider;\n TwitterAuthProvider_Instance: typeof types.TwitterAuthProvider_Instance;\n };\n }\n interface FirebaseApp {\n auth?(): types.FirebaseAuth;\n }\n}\n\n// Create auth components to register with firebase.\n// Provides Auth public APIs.\nfunction registerAuthCompat(instance: _FirebaseNamespace): void {\n instance.INTERNAL.registerComponent(\n new Component(\n AUTH_TYPE,\n container => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app-compat').getImmediate();\n const authProvider = container.getProvider('auth');\n return new Auth(app, authProvider);\n },\n ComponentType.PUBLIC\n )\n .setServiceProps({\n ActionCodeInfo: {\n Operation: {\n EMAIL_SIGNIN: impl.ActionCodeOperation.EMAIL_SIGNIN,\n PASSWORD_RESET: impl.ActionCodeOperation.PASSWORD_RESET,\n RECOVER_EMAIL: impl.ActionCodeOperation.RECOVER_EMAIL,\n REVERT_SECOND_FACTOR_ADDITION:\n impl.ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION,\n VERIFY_AND_CHANGE_EMAIL:\n impl.ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n VERIFY_EMAIL: impl.ActionCodeOperation.VERIFY_EMAIL\n }\n },\n EmailAuthProvider: impl.EmailAuthProvider,\n FacebookAuthProvider: impl.FacebookAuthProvider,\n GithubAuthProvider: impl.GithubAuthProvider,\n GoogleAuthProvider: impl.GoogleAuthProvider,\n OAuthProvider: impl.OAuthProvider,\n SAMLAuthProvider: impl.SAMLAuthProvider,\n PhoneAuthProvider: CompatAuthProvider,\n PhoneMultiFactorGenerator: impl.PhoneMultiFactorGenerator,\n RecaptchaVerifier: CompatRecaptchaVerifier,\n TwitterAuthProvider: impl.TwitterAuthProvider,\n Auth,\n AuthCredential: impl.AuthCredential,\n Error: FirebaseError\n })\n .setInstantiationMode(InstantiationMode.LAZY)\n .setMultipleInstances(false)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterAuthCompat(firebase as _FirebaseNamespace);\n"],"names":["_interopDefaultLegacy","e","default","firebase__default","firebase","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$1","decodeString","bytes","pos","c2","c3","c1","String","fromCharCode","u","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","base64Decode","console","error","getDefaultsFromGlobal","self","window","global","getGlobal","__FIREBASE_DEFAULTS__","getDefaultsFromEnvVariable","process","env","defaultsJsonString","JSON","parse","getDefaultsFromCookie","document","match","cookie","decoded","getDefaults","info","LogLevel","getUA","navigator","isNode","forceEnvironment","_a","Object","prototype","toString","call","isBrowserExtension","runtime","chrome","browser","undefined","id","isReactNative","isIE","ua","indexOf","isIndexedDBAvailable","indexedDB","FirebaseError","constructor","code","message","customData","super","name","setPrototypeOf","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replace","PATTERN","_","key","value","fullMessage","querystring","querystringParams","params","entries","forEach","arrayVal","encodeURIComponent","querystringDecode","obj","tokens","split","token","decodeURIComponent","extractQuerystring","url","queryStart","fragmentStart","substring","ObserverProxy","executor","onNoObservers","observers","unsubscribes","observerCount","task","Promise","resolve","finalized","then","catch","next","forEachObserver","observer","close","complete","subscribe","nextOrObserver","methods","method","implementsAnyMethods","noop","unsub","unsubscribeOne","bind","finalError","fn","sendOne","err","getModularInstance","_delegate","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","args","logLevel","now","Date","toISOString","__rest","s","t","hasOwnProperty","getOwnPropertySymbols","propertyIsEnumerable","__awaiter","thisArg","_arguments","P","generator","reject","fulfilled","step","rejected","result","done","apply","__generator","body","f","y","label","sent","trys","ops","g","verb","throw","return","Symbol","iterator","n","v","op","TypeError","pop","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","ProviderId","FACEBOOK","GITHUB","GOOGLE","PASSWORD","PHONE","TWITTER","ActionCodeOperation","EMAIL_SIGNIN","PASSWORD_RESET","RECOVER_EMAIL","REVERT_SECOND_FACTOR_ADDITION","VERIFY_AND_CHANGE_EMAIL","VERIFY_EMAIL","_prodErrorMap","dependent-sdk-initialized-before-auth","debugErrorMap","admin-restricted-operation","argument-error","app-not-authorized","app-not-installed","captcha-check-failed","code-expired","cordova-not-ready","cors-unsupported","credential-already-in-use","custom-token-mismatch","requires-recent-login","dynamic-link-not-activated","email-change-needs-verification","email-already-in-use","emulator-config-failed","expired-action-code","cancelled-popup-request","internal-error","invalid-app-credential","invalid-app-id","invalid-user-token","invalid-auth-event","invalid-verification-code","invalid-continue-uri","invalid-cordova-configuration","invalid-custom-token","invalid-dynamic-link-domain","invalid-email","invalid-emulator-scheme","invalid-api-key","invalid-cert-hash","invalid-credential","invalid-message-payload","invalid-multi-factor-session","invalid-oauth-provider","invalid-oauth-client-id","unauthorized-domain","invalid-action-code","wrong-password","invalid-persistence-type","invalid-phone-number","invalid-provider-id","invalid-recipient-email","invalid-sender","invalid-verification-id","invalid-tenant-id","login-blocked","missing-android-pkg-name","auth-domain-config-required","missing-app-credential","missing-verification-code","missing-continue-uri","missing-iframe-start","missing-ios-bundle-id","missing-or-invalid-nonce","missing-multi-factor-info","missing-multi-factor-session","missing-phone-number","missing-verification-id","app-deleted","multi-factor-info-not-found","multi-factor-auth-required","account-exists-with-different-credential","network-request-failed","no-auth-event","no-such-provider","null-user","operation-not-allowed","operation-not-supported-in-this-environment","popup-blocked","popup-closed-by-user","provider-already-linked","quota-exceeded","redirect-cancelled-by-user","redirect-operation-pending","rejected-credential","second-factor-already-in-use","maximum-second-factor-count-exceeded","tenant-id-mismatch","timeout","user-token-expired","too-many-requests","unauthorized-continue-uri","unsupported-first-factor","unsupported-persistence-type","unsupported-tenant-operation","unverified-email","user-cancelled","user-not-found","user-disabled","user-mismatch","user-signed-out","weak-password","web-storage-unsupported","already-initialized","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logLevel","_logHandler","_userLogHandler","val","setLogLevel","logHandler","userLogHandler","log","_logError","msg","SDK_VERSION","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","assign","factory","appName","_assertInstanceOf","object","fullParams","slice","_errorFactory","_assert","assertion","debugFail","failure","debugAssert","instanceCache","Map","_getInstance","cls","Function","get","set","_getCurrentUrl","location","href","_isHttpOrHttps","_getCurrentScheme","protocol","Delay","shortDelay","longDelay","isMobile","test","onLine","Math","min","_emulatorUrl","config","path","emulator","startsWith","FetchProvider","initialize","fetchImpl","headersImpl","responseImpl","fetch","headers","Headers","response","Response","SERVER_ERROR_MAP","CREDENTIAL_MISMATCH","MISSING_CUSTOM_TOKEN","INVALID_IDENTIFIER","MISSING_CONTINUE_URI","INVALID_PASSWORD","MISSING_PASSWORD","EMAIL_EXISTS","PASSWORD_LOGIN_DISABLED","INVALID_IDP_RESPONSE","INVALID_PENDING_TOKEN","FEDERATED_USER_ID_ALREADY_LINKED","MISSING_REQ_TYPE","EMAIL_NOT_FOUND","RESET_PASSWORD_EXCEED_LIMIT","EXPIRED_OOB_CODE","INVALID_OOB_CODE","MISSING_OOB_CODE","CREDENTIAL_TOO_OLD_LOGIN_AGAIN","INVALID_ID_TOKEN","TOKEN_EXPIRED","USER_NOT_FOUND","TOO_MANY_ATTEMPTS_TRY_LATER","INVALID_CODE","INVALID_SESSION_INFO","INVALID_TEMPORARY_PROOF","MISSING_SESSION_INFO","SESSION_EXPIRED","MISSING_ANDROID_PACKAGE_NAME","UNAUTHORIZED_DOMAIN","INVALID_OAUTH_CLIENT_ID","ADMIN_ONLY_OPERATION","INVALID_MFA_PENDING_CREDENTIAL","MFA_ENROLLMENT_NOT_FOUND","MISSING_MFA_ENROLLMENT_ID","MISSING_MFA_PENDING_CREDENTIAL","SECOND_FACTOR_EXISTS","SECOND_FACTOR_LIMIT_EXCEEDED","BLOCKING_FUNCTION_ERROR_RESPONSE","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","request","tenantId","async","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","stringify","query","apiKey","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","race","promise","clearNetworkTimeout","json","_makeTaggedError","ok","errorMessage","serverErrorCode","serverErrorMessage","authError","toLowerCase","_performSignInRequest","serverResponse","_serverResponse","host","base","apiScheme","timer","setTimeout","clearTimeout","errorParams","email","phoneNumber","_tokenResponse","utcTimestampToDateString","utcTimestamp","date","Number","isNaN","getTime","toUTCString","secondsStringToMilliseconds","seconds","_parseToken","algorithm","payload","signature","_logoutIfInvalidated","user","bypassAuthState","isUserInvalidated","currentUser","signOut","ProactiveRefresh","isRunning","timerId","errorBackoff","_start","schedule","_stop","getInterval","wasError","interval","stsTokenManager","expirationTime","max","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","creationTime","_copy","metadata","toJSON","_reloadWithoutSaving","idToken","getAccountInfo","users","coreAccount","_notifyReloadListener","newProviderData","providerUserInfo","map","providerId","provider","uid","rawId","displayName","photoURL","photoUrl","providerData","original","newData","deduped","filter","o","some","mergeProviderData","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","localId","emailVerified","StsTokenManager","refreshToken","accessToken","isExpired","updateFromServerResponse","expiresIn","parsedToken","exp","iat","updateTokensAndExpiration","getToken","forceRefresh","refresh","clearRefreshToken","oldToken","grant_type","refresh_token","tokenApiHost","access_token","expires_in","expiresInSec","fromJSON","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","claims","auth_time","signInProvider","authTime","issuedAtTime","signInSecondFactor","reload","userInfo","_onReload","_startProactiveRefresh","_stopProactiveRefresh","_updateTokensIfNecessary","tokensRefreshed","delete","deleteAccount","_redirectEventId","_fromJSON","_b","_c","_d","_e","_f","_g","_h","plainObjectTokenManager","_fromIdTokenResponse","idTokenResponse","InMemoryPersistence","storage","_isAvailable","_set","_get","_remove","_addListener","_key","_listener","_removeListener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","getCurrentUser","blob","removeCurrentUser","savePersistenceForRedirect","setPersistence","newPersistence","persistenceHierarchy","availablePersistences","all","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","userAgent","includes","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","matches","_isIOS","_isMobileBrowser","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","AuthMiddlewareQueue","queue","pushCallback","onAbort","wrappedCallback","index","runMiddleware","nextUser","onAbortStack","beforeStateCallback","reverse","originalMessage","AuthImpl","app","heartbeatServiceProvider","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","lastNotifiedUid","settings","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","redirectUserEventId","storedUserEventId","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","tryRedirectSignIn","directlySetCurrentUser","reloadAndSetCurrentUserOrClear","_overrideRedirectResult","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","language","_getUserLanguage","_delete","updateCurrentUser","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","redirectManager","resolver","_redirectPersistence","_redirectUserForId","currentUid","subscription","cb","addObserver","action","_logFramework","framework","sort","_getFrameworks","X-Client-Version","options","appId","heartbeatsHeader","getImmediate","optional","getHeartbeatsHeader","_castAuth","proxy","createSubscribe","connectAuthEmulator","authInternal","disableWarnings","extractProtocol","port","authority","exec","substr","hostAndPort","bracketedIPv6","parsePort","extractHostAndPort","freeze","attachBanner","el","createElement","sty","style","innerText","position","width","backgroundColor","border","color","bottom","left","margin","zIndex","textAlign","classList","add","appendChild","readyState","addEventListener","emitEmulatorWarning","protocolEnd","portStr","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","resetPassword","updateEmailPassword","sendOobCode","EmailAuthCredential","_email","_password","_tenantId","_fromEmailAndPassword","password","_fromEmailAndCode","oobCode","signInWithPassword","returnSecureToken","signInWithEmailLink$1","signInWithEmailLinkForLinking","signInWithIdp","OAuthCredential","arguments","pendingToken","_fromParams","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","postBody","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","PhoneAuthCredential","_fromVerification","verificationId","verificationCode","_fromTokenResponse","temporaryProof","signInWithPhoneNumber$1","_makeVerificationRequest","linkWithPhoneNumber$1","operation","verifyPhoneNumberForExisting","sessionInfo","ActionCodeURL","actionLink","searchParams","parseMode","continueUrl","parseLink","link","doubleDeepLink","iOSDeepLink","EmailAuthProvider","PROVIDER_ID","credential","credentialWithLink","emailLink","actionCodeUrl","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","OAuthProvider","credentialFromJSON","_credential","rawNonce","credentialFromResult","userCredential","oauthCredentialFromTaggedObject","credentialFromError","tokenResponse","oauthIdToken","oauthAccessToken","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromTaggedObject","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","SAMLAuthCredential","_create","SAMLAuthProvider","samlCredentialFromTaggedObject","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","signUp","UserCredentialImpl","operationType","providerIdForResponse","_forOperation","MultiFactorError","_fromErrorAndOperation","_processCredentialSavingMfaContextIfNecessary","idTokenProvider","providerDataAsNames","Set","pid","unlink","_assertLinkedStatus","deleteProvider","providersLeft","pd","has","_link$1","expected","providerIds","_reauthenticate","parsed","sub","_signInWithCredential","signInWithCredential","linkWithCredential","reauthenticateWithCredential","signInWithCustomToken","customToken","MultiFactorInfoImpl","factorId","mfaEnrollmentId","enrollmentTime","enrolledAt","_fromServerResponse","enrollment","PhoneMultiFactorInfoImpl","phoneInfo","_setActionCodeSettingsOnRequest","actionCodeSettings","dynamicLinkDomain","canHandleCodeInApp","handleCodeInApp","iOS","bundleId","iOSBundleId","android","packageName","androidInstallApp","installApp","androidMinimumVersionCode","minimumVersion","androidPackageName","sendPasswordResetEmail","authModular","requestType","applyActionCode","checkActionCode","newEmail","mfaInfo","multiFactorInfo","previousEmail","sendSignInLinkToEmail","fetchSignInMethodsForEmail","continueUri","signinMethods","identifier","sendEmailVerification","verifyBeforeUpdateEmail","updateProfile","updateProfile$1","passwordProvider","find","updateEmailOrPassword","GenericAdditionalUserInfo","isNewUser","profile","FederatedAdditionalUserInfoWithUsername","username","FacebookAdditionalUserInfo","GithubAdditionalUserInfo","login","GoogleAdditionalUserInfo","TwitterAdditionalUserInfo","screenName","getAdditionalUserInfo","rawUserInfo","kind","filteredProviderId","MultiFactorSessionImpl","_fromIdtoken","_fromMfaPendingCredential","mfaPendingCredential","multiFactorSession","pendingCredential","MultiFactorResolverImpl","session","hints","signInResolver","_fromError","authExtern","mfaResponse","_process","resolveSignIn","assertionExtern","MultiFactorUserImpl","enrolledFactors","_fromUser","getSession","enroll","finalizeMfaResponse","unenroll","infoOrUid","multiFactorUserCache","WeakMap","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","setItem","removeItem","getItem","BrowserLocalPersistence","localStorage","event","poll","onStorageEvent","listeners","localCache","pollTimer","safariLocalStorageNotSynced","top","_isIframe","fallbackToPolling","forAllChangedKeys","keys","newValue","oldValue","detachListener","stopPolling","storedValue","triggerListeners","notifyListeners","documentMode","_oldValue","listener","from","startPolling","setInterval","StorageEvent","clearInterval","attachListener","removeEventListener","size","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","handleEvent","existingInstance","receivers","receiver","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","postMessage","status","promises","handler","origin","reason","_subscribe","eventHandler","_unsubscribe","_generateEventId","prefix","digits","random","floor","Sender","target","removeMessageHandler","messageChannel","port1","onMessage","_send","MessageChannel","completionTimer","start","ackTimer","port2","finally","_window","_isWorker","DB_NAME","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","db","isReadWrite","transaction","objectStore","_openDatabase","open","createObjectStore","keyPath","objectStoreNames","contains","deleteDatabase","_putObject","put","fbase_key","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","_openDb","_withRetries","numAttempts","initializeReceiver","initializeSender","_origin","_poll","keyProcessed","_data","results","serviceWorker","ready","active","_getActiveServiceWorker","notifyServiceWorker","controller","_withPendingWrite","write","getObject","getAllRequest","getAll","keysInResult","localKey","indexedDBLocalPersistence","_loadJS","setAttribute","onload","onerror","charset","getElementsByTagName","_generateCallbackName","MockReCaptcha","counter","_widgets","render","container","parameters","MockWidget","reset","optWidgetId","getResponse","execute","containerOrId","deleted","responseToken","clickHandler","getElementById","isVisible","checkIfDeleted","len","chars","allowedChars","generateRandomAlphaNumericString","expired-callback","expiredCallback","_JSLOAD_CALLBACK","NETWORK_TIMEOUT_DELAY","ReCaptchaLoaderImpl","hostLanguage","librarySeparatelyLoaded","grecaptcha","load","hl","shouldResolveImmediately","recaptcha","widgetId","clearedOneInstance","MockReCaptchaLoaderImpl","RECAPTCHA_VERIFIER_TYPE","DEFAULT_PARAMS","theme","RecaptchaVerifier","destroyed","tokenChangeListeners","renderPromise","isInvisible","makeTokenCallback","_recaptchaLoader","validateStartingState","verify","assertNotDestroyed","getAssertedRecaptcha","tokenChange","makeRenderPromise","_reset","clear","childNodes","node","removeChild","sitekey","hasChildNodes","existing","globalFunc","init","guaranteedEmpty","domReady","siteKey","recaptchaSiteKey","ConfirmationResultImpl","onConfirmation","confirm","authCredential","_verifyPhoneNumber","verifier","recaptchaToken","phoneInfoOptions","phoneEnrollmentInfo","phoneSessionInfo","multiFactorHint","multiFactorUid","phoneSignInInfo","phoneResponseInfo","PhoneAuthProvider","verifyPhoneNumber","phoneOptions","applicationVerifier","_withDefaultResolver","resolverOverride","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_reauth","_link","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","onAuthEvent","urlResponse","getIdpTask","onError","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","cancel","executeNotNull","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","isSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_getAndClearPendingRedirectStatus","_setPendingRedirectStatus","signInWithRedirect","resolverInternal","_openRedirect","_signInWithRedirect","reauthenticateWithRedirect","prepareUserForRedirect","_reauthenticateWithRedirect","linkWithRedirect","_linkWithRedirect","_getRedirectResult","resolverExtern","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","handled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","eventUid","_getProjectConfig","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","domain","currentUrl","hostname","URL","ceUrl","escapedDomainPattern","re","RegExp","matchDomain","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","H","hint","r","L","CP","cachedGApiLoader","_loadGapi","loadGapiIframe","gapi","iframes","getContext","ontimeout","Iframe","cbName","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","height","aria-hidden","tabindex","EID_FROM_APIHOST","_openIframe","context","where","eid","fw","getIframeUrl","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","iframe","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","_open","screen","availHeight","availWidth","scrollbars","optionsString","reduce","accum","_isIOSStandalone","standalone","click","createEvent","initMouseEvent","dispatchEvent","openAsNewWindowIOS","newWin","focus","WIDGET_PATH","EMULATOR_WIDGET_PATH","_getRedirectUrl","authType","redirectUrl","additionalParams","isEmpty","tid","paramsDict","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","initAndGetManager","register","iframeEvent","authEvent","send","PhoneMultiFactorAssertionImpl","_finalizeEnroll","_finalizeSignIn","_fromCredential","phoneVerificationInfo","PhoneMultiFactorGenerator","FACTOR_ID","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","unsubscribe","updateProactiveRefresh","removeAuthTokenListener","_cordovaWindow","_registerComponent","deps","getProvider","authInstance","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","authInternalProvider","registerVersion","getVersionForPlatform","_generateHandlerUrl","BuildInfo","sessionDigest","TextEncoder","encode","buff","ArrayBuffer","view","Uint8Array","stringToArrayBuffer","buf","crypto","subtle","digest","arr","num","padStart","computeSha256","_performRedirect","handlerUrl","cordova","plugins","browsertab","isAvailable","browserTabIsAvailable","iabRef","openUrl","InAppBrowser","SESSION_ID_LENGTH","CordovaAuthEventManager","passiveListeners","initPromise","resolveInialized","addPassiveListener","removePassiveListener","resetRedirect","initialized","_generateNewEvent","idx","generateSessionId","_getAndRemoveEvent","persistenceKey","_eventFromPartialAndUrl","partialEvent","callbackUrl","searchParamsOrEmpty","iOSDoubleDeepLink","errorObject","parseJsonOrNull","cordovaPopupRedirectResolver","attachCallbackListeners","win","universalLinks","missingPlugin","_k","_j","eventListener","cleanup","onCloseTimer","authEventSeen","closeBrowserTab","resumed","visibilityChanged","visibilityState","_waitForAppResume","_cb","iosBundleId","handleOpenURL","noEventTimeout","generateNoEvent","universalLinksCb","eventData","finalEvent","existingHandleOpenURL","packagePrefix","_isAndroidOrIosCordovaScheme","_isLocalStorageNotSynchronized","_isWebStorageSupported","impl._generateEventId","_isPopupRedirectSupported","_isLikelyCordova","Persistence","LOCAL","NONE","SESSION","exp._assert","PERSISTENCE_KEY","_savePersistenceForRedirect","getSessionStorageIfAvailable","exp._persistenceKeyName","CompatPopupRedirectResolver","selectUnderlyingResolver","assertedUnderlyingResolver","defineProperty","browserResolver","underlyingResolver","timeoutId","_isCordova","isCordova","cordovaResolver","exp._getInstance","exp.browserPopupRedirectResolver","exp.cordovaPopupRedirectResolver","exp.browserSessionPersistence","exp._getRedirectResult","exp._overrideRedirectResult","unwrap","attachExtraErrorFields","MultiFactorResolver","errorInternal","credentialFromObject","credErr","exp.PhoneAuthProvider","exp.ProviderId","exp.GoogleAuthProvider","exp.FacebookAuthProvider","exp.GithubAuthProvider","exp.TwitterAuthProvider","exp.SAMLAuthCredential","exp.OAuthCredential","exp.OAuthProvider","convertCredential","credentialPromise","additionalUserInfo","exp.getAdditionalUserInfo","User","getOrCreate","convertConfirmationResult","confirmationResultPromise","confirmationResultExp","wrapped","USER_MAP","linkAndRetrieveDataWithCredential","exp.linkWithCredential","linkWithPhoneNumber","appVerifier","exp.linkWithPhoneNumber","linkWithPopup","exp.linkWithPopup","exp._castAuth","exp.linkWithRedirect","reauthenticateAndRetrieveDataWithCredential","exp.reauthenticateWithCredential","reauthenticateWithPhoneNumber","exp.reauthenticateWithPhoneNumber","reauthenticateWithPopup","exp.reauthenticateWithPopup","exp.reauthenticateWithRedirect","exp.sendEmailVerification","exp.unlink","updateEmail","updatePassword","newPassword","updatePhoneNumber","phoneCredential","exp.updatePhoneNumber","exp.updateProfile","exp.verifyBeforeUpdateEmail","multiFactor","userModular","Auth","useEmulator","exp.connectAuthEmulator","exp.applyActionCode","exp.checkActionCode","confirmPasswordReset","exp.confirmPasswordReset","createUserWithEmailAndPassword","exp.createUserWithEmailAndPassword","fetchProvidersForEmail","exp.fetchSignInMethodsForEmail","isSignInWithEmailLink","getRedirectResult","exp.getRedirectResult","addFrameworkForLogging","errorFn","wrapObservers","exp.sendSignInLinkToEmail","exp.sendPasswordResetEmail","values","converted","exp\r\n ._getInstance","exp.indexedDBLocalPersistence","isIndexedDBFullySupported","exp.browserLocalPersistence","exp.inMemoryPersistence","exp._fail","signInAndRetrieveDataWithCredential","signInAnonymously","exp.signInAnonymously","exp.signInWithCredential","exp.signInWithCustomToken","signInWithEmailAndPassword","signInWithEmailLink","exp.signInWithEmailLink","signInWithPhoneNumber","exp.signInWithPhoneNumber","signInWithPopup","exp.signInWithPopup","exp.signInWithRedirect","verifyPasswordResetCode","exp.verifyPasswordResetCode","linkUnderlyingAuth","_this","isInitialized","persistences","_getPersistencesFromRedirect","_i","buildPersistenceHierarchy","exp.debugErrorMap","oldNext","exp.RecaptchaVerifier","INTERNAL","registerComponent","authProvider","ActionCodeInfo","Operation","impl.ActionCodeOperation","impl.EmailAuthProvider","impl.FacebookAuthProvider","impl.GithubAuthProvider","impl.GoogleAuthProvider","impl.OAuthProvider","impl.SAMLAuthProvider","CompatAuthProvider","impl.PhoneMultiFactorGenerator","CompatRecaptchaVerifier","impl.TwitterAuthProvider","impl.AuthCredential"],"mappings":"8WAAA,SAAAA,EAAAC,GAAA,OAAAA,GAAA,iBAAAA,GAAA,YAAAA,EAAAA,EAAA,CAAAC,QAAAD,GAAA,IAAAE,EAAAH,EAAAI,IAoFA,MAuEMC,EAAS,CAIXC,eAAgB,KAIhBC,eAAgB,KAKhBC,sBAAuB,KAKvBC,sBAAuB,KAKvBC,kBAAmB,iEAInBC,mBACI,OAAOC,KAAKF,kBAAoB,OAKpCG,2BACI,OAAOD,KAAKF,kBAAoB,OASpCI,mBAAoC,mBAATC,KAU3BC,gBAAgBC,EAAOC,GACnB,IAAKC,MAAMC,QAAQH,GACf,MAAMI,MAAM,iDAEhBT,KAAKU,QACL,IAAMC,EAAgBL,EAChBN,KAAKJ,sBACLI,KAAKN,eACX,MAAMkB,EAAS,GACf,IAAK,IAAIC,EAAI,EAAGA,EAAIR,EAAMS,OAAQD,GAAK,EAAG,CACtC,IAAME,EAAQV,EAAMQ,GACdG,EAAYH,EAAI,EAAIR,EAAMS,OAC1BG,EAAQD,EAAYX,EAAMQ,EAAI,GAAK,EACnCK,EAAYL,EAAI,EAAIR,EAAMS,OAC1BK,EAAQD,EAAYb,EAAMQ,EAAI,GAAK,EAGzC,IAAIO,GAAqB,GAARH,IAAiB,EAAME,GAAS,EAC7CE,EAAmB,GAARF,EACVD,I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