{"version":3,"file":"firebase.39PqHtRz.js","sources":["../../node_modules/@firebase/util/dist/index.esm2017.js","../../node_modules/@firebase/component/dist/esm/index.esm2017.js","../../node_modules/@firebase/logger/dist/esm/index.esm2017.js","../../node_modules/idb/build/wrap-idb-value.js","../../node_modules/idb/build/index.js","../../node_modules/@firebase/app/dist/esm/index.esm2017.js","../../node_modules/@firebase/webchannel-wrapper/dist/bloom-blob/esm/bloom_blob_es2018.js","../../node_modules/@firebase/webchannel-wrapper/dist/webchannel-blob/esm/webchannel_blob_es2018.js","../../node_modules/@firebase/firestore/dist/index.esm2017.js","../../node_modules/firebase/app/dist/esm/index.esm.js","../../node_modules/tslib/tslib.es6.mjs","../../node_modules/@firebase/auth/dist/esm2017/index-68602d24.js","../../node_modules/@firebase/database/dist/index.esm2017.js"],"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 new DecodeBase64StringError();\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 * An error encountered while decoding base64 string.\r\n */\r\nclass DecodeBase64StringError extends Error {\r\n constructor() {\r\n super(...arguments);\r\n this.name = 'DecodeBase64StringError';\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 promisified 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 * Note: This will return true for certain test frameworks that are incompletely\r\n * mimicking a browser, and should not lead to assuming all browser APIs are\r\n * available.\r\n */\r\nfunction isBrowser() {\r\n return typeof window !== 'undefined' || isWebWorker();\r\n}\r\n/**\r\n * Detect Web Worker context.\r\n */\r\nfunction isWebWorker() {\r\n return (typeof WorkerGlobalScope !== 'undefined' &&\r\n typeof self !== 'undefined' &&\r\n self instanceof WorkerGlobalScope);\r\n}\r\n/**\r\n * Detect Cloudflare Worker context.\r\n */\r\nfunction isCloudflareWorker() {\r\n return (typeof navigator !== 'undefined' &&\r\n navigator.userAgent === 'Cloudflare-Workers');\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 &&\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 = {\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('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 synchronously 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 *

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 *

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, DecodeBase64StringError, 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, isCloudflareWorker, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, isWebWorker, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\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 multiple 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/cannot 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","/**\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","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, isBrowser, isWebWorker, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\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 PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\r\n}\n\nconst name$q = \"@firebase/app\";\nconst version$1 = \"0.10.13\";\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 logger = new Logger('@firebase/app');\n\nconst name$p = \"@firebase/app-compat\";\n\nconst name$o = \"@firebase/analytics-compat\";\n\nconst name$n = \"@firebase/analytics\";\n\nconst name$m = \"@firebase/app-check-compat\";\n\nconst name$l = \"@firebase/app-check\";\n\nconst name$k = \"@firebase/auth\";\n\nconst name$j = \"@firebase/auth-compat\";\n\nconst name$i = \"@firebase/database\";\n\nconst name$h = \"@firebase/data-connect\";\n\nconst name$g = \"@firebase/database-compat\";\n\nconst name$f = \"@firebase/functions\";\n\nconst name$e = \"@firebase/functions-compat\";\n\nconst name$d = \"@firebase/installations\";\n\nconst name$c = \"@firebase/installations-compat\";\n\nconst name$b = \"@firebase/messaging\";\n\nconst name$a = \"@firebase/messaging-compat\";\n\nconst name$9 = \"@firebase/performance\";\n\nconst name$8 = \"@firebase/performance-compat\";\n\nconst name$7 = \"@firebase/remote-config\";\n\nconst name$6 = \"@firebase/remote-config-compat\";\n\nconst name$5 = \"@firebase/storage\";\n\nconst name$4 = \"@firebase/storage-compat\";\n\nconst name$3 = \"@firebase/firestore\";\n\nconst name$2 = \"@firebase/vertexai-preview\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"10.14.1\";\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 default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$q]: 'fire-core',\r\n [name$p]: 'fire-core-compat',\r\n [name$n]: 'fire-analytics',\r\n [name$o]: 'fire-analytics-compat',\r\n [name$l]: 'fire-app-check',\r\n [name$m]: 'fire-app-check-compat',\r\n [name$k]: 'fire-auth',\r\n [name$j]: 'fire-auth-compat',\r\n [name$i]: 'fire-rtdb',\r\n [name$h]: 'fire-data-connect',\r\n [name$g]: 'fire-rtdb-compat',\r\n [name$f]: 'fire-fn',\r\n [name$e]: 'fire-fn-compat',\r\n [name$d]: 'fire-iid',\r\n [name$c]: 'fire-iid-compat',\r\n [name$b]: 'fire-fcm',\r\n [name$a]: 'fire-fcm-compat',\r\n [name$9]: 'fire-perf',\r\n [name$8]: 'fire-perf-compat',\r\n [name$7]: 'fire-rc',\r\n [name$6]: 'fire-rc-compat',\r\n [name$5]: 'fire-gcs',\r\n [name$4]: 'fire-gcs-compat',\r\n [name$3]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n [name$2]: 'fire-vertex',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\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 * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * @internal\r\n */\r\nconst _serverApps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n for (const serverApp of _serverApps.values()) {\r\n _addComponent(serverApp, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n *\r\n * @param obj - an object of type FirebaseApp or FirebaseOptions.\r\n *\r\n * @returns true if the provide object is of type FirebaseApp.\r\n *\r\n * @internal\r\n */\r\nfunction _isFirebaseApp(obj) {\r\n return obj.options !== undefined;\r\n}\r\n/**\r\n *\r\n * @param obj - an object of type FirebaseApp.\r\n *\r\n * @returns true if the provided object is of type FirebaseServerAppImpl.\r\n *\r\n * @internal\r\n */\r\nfunction _isFirebaseServerApp(obj) {\r\n return obj.settings !== undefined;\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\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 ERRORS = {\r\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call initializeApp() first',\r\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}'\",\r\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',\r\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\r\n [\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\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 FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 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 FirebaseServerAppImpl extends FirebaseAppImpl {\r\n constructor(options, serverConfig, name, container) {\r\n // Build configuration parameters for the FirebaseAppImpl base class.\r\n const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined\r\n ? serverConfig.automaticDataCollectionEnabled\r\n : false;\r\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\r\n const config = {\r\n name,\r\n automaticDataCollectionEnabled\r\n };\r\n if (options.apiKey !== undefined) {\r\n // Construct the parent FirebaseAppImp object.\r\n super(options, config, container);\r\n }\r\n else {\r\n const appImpl = options;\r\n super(appImpl.options, config, container);\r\n }\r\n // Now construct the data for the FirebaseServerAppImpl.\r\n this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig);\r\n this._finalizationRegistry = null;\r\n if (typeof FinalizationRegistry !== 'undefined') {\r\n this._finalizationRegistry = new FinalizationRegistry(() => {\r\n this.automaticCleanup();\r\n });\r\n }\r\n this._refCount = 0;\r\n this.incRefCount(this._serverConfig.releaseOnDeref);\r\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry\r\n // will never trigger.\r\n this._serverConfig.releaseOnDeref = undefined;\r\n serverConfig.releaseOnDeref = undefined;\r\n registerVersion(name$q, version$1, 'serverapp');\r\n }\r\n toJSON() {\r\n return undefined;\r\n }\r\n get refCount() {\r\n return this._refCount;\r\n }\r\n // Increment the reference count of this server app. If an object is provided, register it\r\n // with the finalization registry.\r\n incRefCount(obj) {\r\n if (this.isDeleted) {\r\n return;\r\n }\r\n this._refCount++;\r\n if (obj !== undefined && this._finalizationRegistry !== null) {\r\n this._finalizationRegistry.register(obj, this);\r\n }\r\n }\r\n // Decrement the reference count.\r\n decRefCount() {\r\n if (this.isDeleted) {\r\n return 0;\r\n }\r\n return --this._refCount;\r\n }\r\n // Invoked by the FinalizationRegistry callback to note that this app should go through its\r\n // reference counts and delete itself if no reference count remain. The coordinating logic that\r\n // handles this is in deleteApp(...).\r\n automaticCleanup() {\r\n void deleteApp(this);\r\n }\r\n get settings() {\r\n this.checkDestroyed();\r\n return this._serverConfig;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */);\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 * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\nfunction initializeServerApp(_options, _serverAppConfig) {\r\n if (isBrowser() && !isWebWorker()) {\r\n // FirebaseServerApp isn't designed to be run in browsers.\r\n throw ERROR_FACTORY.create(\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);\r\n }\r\n if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {\r\n _serverAppConfig.automaticDataCollectionEnabled = false;\r\n }\r\n let appOptions;\r\n if (_isFirebaseApp(_options)) {\r\n appOptions = _options.options;\r\n }\r\n else {\r\n appOptions = _options;\r\n }\r\n // Build an app name based on a hash of the configuration options.\r\n const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);\r\n // However, Do not mangle the name based on releaseOnDeref, since it will vary between the\r\n // construction of FirebaseServerApp instances. For example, if the object is the request headers.\r\n if (nameObj.releaseOnDeref !== undefined) {\r\n delete nameObj.releaseOnDeref;\r\n }\r\n const hashCode = (s) => {\r\n return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);\r\n };\r\n if (_serverAppConfig.releaseOnDeref !== undefined) {\r\n if (typeof FinalizationRegistry === 'undefined') {\r\n throw ERROR_FACTORY.create(\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});\r\n }\r\n }\r\n const nameString = '' + hashCode(JSON.stringify(nameObj));\r\n const existingApp = _serverApps.get(nameString);\r\n if (existingApp) {\r\n existingApp.incRefCount(_serverAppConfig.releaseOnDeref);\r\n return existingApp;\r\n }\r\n const container = new ComponentContainer(nameString);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);\r\n _serverApps.set(nameString, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n let cleanupProviders = false;\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n cleanupProviders = true;\r\n _apps.delete(name);\r\n }\r\n else if (_serverApps.has(name)) {\r\n const firebaseServerApp = app;\r\n if (firebaseServerApp.decRefCount() <= 0) {\r\n _serverApps.delete(name);\r\n cleanupProviders = true;\r\n }\r\n }\r\n if (cleanupProviders) {\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\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 DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n try {\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n catch (e) {\r\n // Safari/iOS browsers throw occasional exceptions on\r\n // db.createObjectStore() that may be a bug. Avoid blocking\r\n // the rest of the app functionality.\r\n console.warn(e);\r\n }\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME);\r\n const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\r\n // We already have the value but tx.done can throw,\r\n // so we need to await it here to catch errors\r\n await tx.done;\r\n return result;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n await tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\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 MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n var _a, _b;\r\n try {\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n // If we failed to construct a heartbeats cache, then return immediately.\r\n if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {\r\n return;\r\n }\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats =\r\n this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n catch (e) {\r\n logger.warn(e);\r\n }\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n var _a;\r\n try {\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n catch (e) {\r\n logger.warn(e);\r\n return '';\r\n }\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {\r\n return idbHeartbeatObject;\r\n }\r\n else {\r\n return { heartbeats: [] };\r\n }\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\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\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$q, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$q, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nvar bloom_blob_es2018 = {};\n\n/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n\nvar Integer;\nvar Md5;\n(function() {var h;/** @license\n\n Copyright The Closure Library Authors.\n SPDX-License-Identifier: Apache-2.0\n*/\nfunction k(f,a){function c(){}c.prototype=a.prototype;f.D=a.prototype;f.prototype=new c;f.prototype.constructor=f;f.C=function(d,e,g){for(var b=Array(arguments.length-2),r=2;re;++e)d[e]=a.charCodeAt(c++)|a.charCodeAt(c++)<<8|a.charCodeAt(c++)<<16|a.charCodeAt(c++)<<24;else for(e=0;16>e;++e)d[e]=a[c++]|a[c++]<<8|a[c++]<<16|a[c++]<<24;a=f.g[0];c=f.g[1];e=f.g[2];var g=f.g[3];var b=a+(g^c&(e^g))+d[0]+3614090360&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[1]+3905402710&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[2]+606105819&4294967295;e=g+(b<<17&4294967295|b>>>15);\nb=c+(a^e&(g^a))+d[3]+3250441966&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[4]+4118548399&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[5]+1200080426&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[6]+2821735955&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[7]+4249261313&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[8]+1770035416&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[9]+2336552879&4294967295;g=a+(b<<12&4294967295|\nb>>>20);b=e+(c^g&(a^c))+d[10]+4294925233&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[11]+2304563134&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[12]+1804603682&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[13]+4254626195&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[14]+2792965006&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[15]+1236535329&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(e^g&(c^e))+d[1]+4129170786&4294967295;a=c+(b<<\n5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[6]+3225465664&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[11]+643717713&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[0]+3921069994&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[5]+3593408605&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[10]+38016083&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[15]+3634488961&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[4]+3889429448&4294967295;c=\ne+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[9]+568446438&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[14]+3275163606&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[3]+4107603335&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[8]+1163531501&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[13]+2850285829&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[2]+4243563512&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[7]+1735328473&4294967295;\ne=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[12]+2368359562&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(c^e^g)+d[5]+4294588738&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[8]+2272392833&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[11]+1839030562&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[14]+4259657740&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[1]+2763975236&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[4]+1272893353&4294967295;g=a+(b<<11&4294967295|\nb>>>21);b=e+(g^a^c)+d[7]+4139469664&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[10]+3200236656&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[13]+681279174&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[0]+3936430074&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[3]+3572445317&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[6]+76029189&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[9]+3654602809&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[12]+\n3873151461&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[15]+530742520&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[2]+3299628645&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(e^(c|~g))+d[0]+4096336452&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[7]+1126891415&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[14]+2878612391&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[5]+4237533241&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[12]+1700485571&\n4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[3]+2399980690&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[10]+4293915773&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[1]+2240044497&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[8]+1873313359&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[15]+4264355552&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[6]+2734768916&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[13]+1309151649&\n4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[4]+4149444226&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[11]+3174756917&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[2]+718787259&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[9]+3951481745&4294967295;f.g[0]=f.g[0]+a&4294967295;f.g[1]=f.g[1]+(e+(b<<21&4294967295|b>>>11))&4294967295;f.g[2]=f.g[2]+e&4294967295;f.g[3]=f.g[3]+g&4294967295;}\nm.prototype.u=function(f,a){void 0===a&&(a=f.length);for(var c=a-this.blockSize,d=this.B,e=this.h,g=0;gthis.h?this.blockSize:2*this.blockSize)-this.h);f[0]=128;for(var a=1;aa;++a)for(var d=0;32>d;d+=8)f[c++]=this.g[a]>>>d&255;return f};function p(f,a){var c=q;return Object.prototype.hasOwnProperty.call(c,f)?c[f]:c[f]=a(f)}function t(f,a){this.h=a;for(var c=[],d=!0,e=f.length-1;0<=e;e--){var g=f[e]|0;d&&g==a||(c[e]=g,d=!1);}this.g=c;}var q={};function u(f){return -128<=f&&128>f?p(f,function(a){return new t([a|0],0>a?-1:0)}):new t([f|0],0>f?-1:0)}function v(f){if(isNaN(f)||!isFinite(f))return w;if(0>f)return x(v(-f));for(var a=[],c=1,d=0;f>=c;d++)a[d]=f/c|0,c*=4294967296;return new t(a,0)}\nfunction y(f,a){if(0==f.length)throw Error(\"number format error: empty string\");a=a||10;if(2>a||36g?(g=v(Math.pow(a,g)),d=d.j(g).add(v(b))):(d=d.j(c),d=d.add(v(b)));}return d}var w=u(0),z=u(1),A=u(16777216);h=t.prototype;\nh.m=function(){if(B(this))return -x(this).m();for(var f=0,a=1,c=0;cf||36>>0).toString(f);c=e;if(C(c))return g+d;for(;6>g.length;)g=\"0\"+g;d=g+d;}};\nh.i=function(f){return 0>f?0:f>>16)+(this.i(e)>>>16)+(f.i(e)>>>16);d=b>>>16;g&=65535;b&=65535;c[e]=b<<16|g;}return new t(c,c[c.length-1]&-2147483648?-1:0)};function F(f,a){return f.add(x(a))}\nh.j=function(f){if(C(this)||C(f))return w;if(B(this))return B(f)?x(this).j(x(f)):x(x(this).j(f));if(B(f))return x(this.j(x(f)));if(0>this.l(A)&&0>f.l(A))return v(this.m()*f.m());for(var a=this.g.length+f.g.length,c=[],d=0;d<2*a;d++)c[d]=0;for(d=0;d>>16,b=this.i(d)&65535,r=f.i(e)>>>16,E=f.i(e)&65535;c[2*d+2*e]+=b*E;G(c,2*d+2*e);c[2*d+2*e+1]+=g*E;G(c,2*d+2*e+1);c[2*d+2*e+1]+=b*r;G(c,2*d+2*e+1);c[2*d+2*e+2]+=g*r;G(c,2*d+2*e+2);}for(d=0;d<\na;d++)c[d]=c[2*d+1]<<16|c[2*d];for(d=a;d<2*a;d++)c[d]=0;return new t(c,0)};function G(f,a){for(;(f[a]&65535)!=f[a];)f[a+1]+=f[a]>>>16,f[a]&=65535,a++;}function H(f,a){this.g=f;this.h=a;}\nfunction D(f,a){if(C(a))throw Error(\"division by zero\");if(C(f))return new H(w,w);if(B(f))return a=D(x(f),a),new H(x(a.g),x(a.h));if(B(a))return a=D(f,x(a)),new H(x(a.g),a.h);if(30=d.l(f);)c=I(c),d=I(d);var e=J(c,1),g=J(d,1);d=J(d,2);for(c=J(c,2);!C(d);){var b=g.add(d);0>=b.l(f)&&(e=e.add(c),g=b);d=J(d,1);c=J(c,1);}a=F(f,e.j(a));return new H(e,a)}for(e=w;0<=f.l(a);){c=Math.max(1,Math.floor(f.m()/\na.m()));d=Math.ceil(Math.log(c)/Math.LN2);d=48>=d?1:Math.pow(2,d-48);g=v(c);for(b=g.j(a);B(b)||0>>31;return new t(c,f.h)}function J(f,a){var c=a>>5;a%=32;for(var d=f.g.length-c,e=[],g=0;g>>a|f.i(g+c+1)<<32-a:f.i(g+c);return new t(e,f.h)}m.prototype.digest=m.prototype.v;m.prototype.reset=m.prototype.s;m.prototype.update=m.prototype.u;Md5 = bloom_blob_es2018.Md5=m;t.prototype.add=t.prototype.add;t.prototype.multiply=t.prototype.j;t.prototype.modulo=t.prototype.A;t.prototype.compare=t.prototype.l;t.prototype.toNumber=t.prototype.m;t.prototype.toString=t.prototype.toString;t.prototype.getBits=t.prototype.i;t.fromNumber=v;t.fromString=y;Integer = bloom_blob_es2018.Integer=t;}).apply( typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {});\n\nexport { Integer, Md5, bloom_blob_es2018 as default };\n//# sourceMappingURL=bloom_blob_es2018.js.map\n","var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nvar webchannel_blob_es2018 = {};\n\n/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n\nvar XhrIo;\nvar FetchXmlHttpFactory;\nvar WebChannel;\nvar EventType;\nvar ErrorCode;\nvar Stat;\nvar Event;\nvar getStatEventTarget;\nvar createWebChannelTransport;\n(function() {var h,aa=\"function\"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};function ba(a){a=[\"object\"==typeof globalThis&&globalThis,a,\"object\"==typeof window&&window,\"object\"==typeof self&&self,\"object\"==typeof commonjsGlobal&&commonjsGlobal];for(var b=0;b{throw a;},0);}function xa(){var a=za;let b=null;a.g&&(b=a.g,a.g=a.g.next,a.g||(a.h=null),b.next=null);return b}class Aa{constructor(){this.h=this.g=null;}add(a,b){const c=Ba.get();c.set(a,b);this.h?this.h.next=c:this.g=c;this.h=c;}}var Ba=new na(()=>new Ca,a=>a.reset());class Ca{constructor(){this.next=this.g=this.h=null;}set(a,b){this.h=a;this.g=b;this.next=null;}reset(){this.next=this.g=this.h=null;}}let x,y=!1,za=new Aa,Ea=()=>{const a=k.Promise.resolve(void 0);x=()=>{a.then(Da);};};var Da=()=>{for(var a;a=xa();){try{a.h.call(a.g);}catch(c){wa(c);}var b=Ba;b.j(a);100>b.h&&(b.h++,a.next=b.g,b.g=a);}y=!1;};function z(){this.s=this.s;this.C=this.C;}z.prototype.s=!1;z.prototype.ma=function(){this.s||(this.s=!0,this.N());};z.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()();};function A(a,b){this.type=a;this.g=this.target=b;this.defaultPrevented=!1;}A.prototype.h=function(){this.defaultPrevented=!0;};var Fa=function(){if(!k.addEventListener||!Object.defineProperty)return !1;var a=!1,b=Object.defineProperty({},\"passive\",{get:function(){a=!0;}});try{const c=()=>{};k.addEventListener(\"test\",c,b);k.removeEventListener(\"test\",c,b);}catch(c){}return a}();function C(a,b){A.call(this,a?a.type:\"\");this.relatedTarget=this.g=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=0;this.key=\"\";this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.pointerId=0;this.pointerType=\"\";this.i=null;if(a){var c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.g=b;if(b=a.relatedTarget){if(pa){a:{try{oa(b.nodeName);var e=!0;break a}catch(f){}e=\n!1;}e||(b=null);}}else \"mouseover\"==c?b=a.fromElement:\"mouseout\"==c&&(b=a.toElement);this.relatedTarget=b;d?(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.clientX=void 0!==a.clientX?a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.key=a.key||\"\";this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=\na.shiftKey;this.metaKey=a.metaKey;this.pointerId=a.pointerId||0;this.pointerType=\"string\"===typeof a.pointerType?a.pointerType:Ga[a.pointerType]||\"\";this.state=a.state;this.i=a;a.defaultPrevented&&C.aa.h.call(this);}}r(C,A);var Ga={2:\"touch\",3:\"pen\",4:\"mouse\"};C.prototype.h=function(){C.aa.h.call(this);var a=this.i;a.preventDefault?a.preventDefault():a.returnValue=!1;};var D=\"closure_listenable_\"+(1E6*Math.random()|0);var Ha=0;function Ia(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.ha=e;this.key=++Ha;this.da=this.fa=!1;}function Ja(a){a.da=!0;a.listener=null;a.proxy=null;a.src=null;a.ha=null;}function Ka(a){this.src=a;this.g={};this.h=0;}Ka.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.g[f];a||(a=this.g[f]=[],this.h++);var g=La(a,b,d,e);-1>>0);function Sa(a){if(\"function\"===typeof a)return a;a[$a]||(a[$a]=function(b){return a.handleEvent(b)});return a[$a]}function E(){z.call(this);this.i=new Ka(this);this.M=this;this.F=null;}r(E,z);E.prototype[D]=!0;E.prototype.removeEventListener=function(a,b,c,d){Ya(this,a,b,c,d);};\nfunction F(a,b){var c,d=a.F;if(d)for(c=[];d;d=d.F)c.push(d);a=a.M;d=b.type||b;if(\"string\"===typeof b)b=new A(b,a);else if(b instanceof A)b.target=b.target||a;else {var e=b;b=new A(d,a);ua(b,e);}e=!0;if(c)for(var f=c.length-1;0<=f;f--){var g=b.g=c[f];e=ab(g,d,!0,b)&&e;}g=b.g=a;e=ab(g,d,!0,b)&&e;e=ab(g,d,!1,b)&&e;if(c)for(f=0;f{a.g=null;a.i&&(a.i=!1,cb(a));},a.l);const b=a.h;a.h=null;a.m.apply(null,b);}class eb extends z{constructor(a,b){super();this.m=a;this.l=b;this.h=null;this.i=!1;this.g=null;}j(a){this.h=arguments;this.g?this.i=!0:cb(this);}N(){super.N();this.g&&(k.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null);}}function G(a){z.call(this);this.h=a;this.g={};}r(G,z);var fb=[];function gb(a){qa(a.g,function(b,c){this.g.hasOwnProperty(c)&&Za(b);},a);a.g={};}G.prototype.N=function(){G.aa.N.call(this);gb(this);};G.prototype.handleEvent=function(){throw Error(\"EventHandler.handleEvent not implemented\");};var hb=k.JSON.stringify;var ib=k.JSON.parse;var jb=class{stringify(a){return k.JSON.stringify(a,void 0)}parse(a){return k.JSON.parse(a,void 0)}};function kb(){}kb.prototype.h=null;function lb(a){return a.h||(a.h=a.i())}function mb(){}var H={OPEN:\"a\",kb:\"b\",Ja:\"c\",wb:\"d\"};function nb(){A.call(this,\"d\");}r(nb,A);function ob(){A.call(this,\"c\");}r(ob,A);var I={},pb=null;function qb(){return pb=pb||new E}I.La=\"serverreachability\";function rb(a){A.call(this,I.La,a);}r(rb,A);function J(a){const b=qb();F(b,new rb(b));}I.STAT_EVENT=\"statevent\";function sb(a,b){A.call(this,I.STAT_EVENT,a);this.stat=b;}r(sb,A);function K(a){const b=qb();F(b,new sb(b,a));}I.Ma=\"timingevent\";function tb(a,b){A.call(this,I.Ma,a);this.size=b;}r(tb,A);\nfunction ub(a,b){if(\"function\"!==typeof a)throw Error(\"Fn must not be null and must be a function\");return k.setTimeout(function(){a();},b)}function vb(){this.g=!0;}vb.prototype.xa=function(){this.g=!1;};function wb(a,b,c,d,e,f){a.info(function(){if(a.g)if(f){var g=\"\";for(var m=f.split(\"&\"),q=0;qd.length)){var e=d[1];if(Array.isArray(e)&&!(1>e.length)){var f=e[0];if(\"noop\"!=f&&\"stop\"!=f&&\"close\"!=f)for(var g=1;gw)&&(3!=w||this.g&&(this.h.h||this.g.oa()||Nb(this.g)))){this.J||4!=w||7==b||(8==b||0>=O?J(3):J(2));Ob(this);var c=this.g.Z();this.X=c;b:if(Pb(this)){var d=Nb(this.g);a=\"\";var e=d.length,f=4==P(this.g);if(!this.h.i){if(\"undefined\"===typeof TextDecoder){Q(this);Qb(this);var g=\"\";break b}this.h.i=new k.TextDecoder;}for(b=0;bb.length)return Gb;b=b.slice(d,d+c);a.C=d+c;return b}M.prototype.cancel=function(){this.J=!0;Q(this);};function Kb(a){a.S=Date.now()+a.I;Wb(a,a.I);}function Wb(a,b){if(null!=a.B)throw Error(\"WatchDog timer not null\");a.B=ub(p(a.ba,a),b);}function Ob(a){a.B&&(k.clearTimeout(a.B),a.B=null);}\nM.prototype.ba=function(){this.B=null;const a=Date.now();0<=a-this.S?(zb(this.i,this.A),2!=this.L&&(J(),K(17)),Q(this),this.s=2,Qb(this)):Wb(this,this.S-a);};function Qb(a){0==a.j.G||a.J||Ub(a.j,a);}function Q(a){Ob(a);var b=a.M;b&&\"function\"==typeof b.ma&&b.ma();a.M=null;gb(a.U);a.g&&(b=a.g,a.g=null,b.abort(),b.ma());}\nfunction Rb(a,b){try{var c=a.j;if(0!=c.G&&(c.g==a||Xb(c.h,a)))if(!a.K&&Xb(c.h,a)&&3==c.G){try{var d=c.Da.g.parse(b);}catch(l){d=null;}if(Array.isArray(d)&&3==d.length){var e=d;if(0==e[0])a:{if(!c.u){if(c.g)if(c.g.F+3E3e[2]&&c.F&&0==c.v&&!c.C&&(c.C=ub(p(c.Za,c),6E3));if(1>=ac(c.h)&&c.ca){try{c.ca();}catch(l){}c.ca=void 0;}}else R(c,11);}else if((a.K||c.g==a)&&Yb(c),!t(b))for(e=c.Da.g.parse(b),b=0;b=a.j:!1}function ac(a){return a.h?1:a.g?a.g.size:0}function Xb(a,b){return a.h?a.h==b:a.g?a.g.has(b):!1}\nfunction bc(a,b){a.g?a.g.add(b):a.h=b;}function dc(a,b){a.h&&a.h==b?a.h=null:a.g&&a.g.has(b)&&a.g.delete(b);}ic.prototype.cancel=function(){this.i=kc(this);if(this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const a of this.g.values())a.cancel();this.g.clear();}};function kc(a){if(null!=a.h)return a.i.concat(a.h.D);if(null!=a.g&&0!==a.g.size){let b=a.i;for(const c of a.g.values())b=b.concat(c.D);return b}return la(a.i)}function lc(a){if(a.V&&\"function\"==typeof a.V)return a.V();if(\"undefined\"!==typeof Map&&a instanceof Map||\"undefined\"!==typeof Set&&a instanceof Set)return Array.from(a.values());if(\"string\"===typeof a)return a.split(\"\");if(ha(a)){for(var b=[],c=a.length,d=0;db)throw Error(\"Bad port number \"+b);a.s=b;}else a.s=null;}function tc(a,b,c){b instanceof sc?(a.i=b,Ac(a.i,a.h)):(c||(b=vc(b,Bc)),a.i=new sc(b,a.h));}function S(a,b,c){a.i.set(b,c);}function Ib(a){S(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36));return a}\nfunction uc(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}function vc(a,b,c){return \"string\"===typeof a?(a=encodeURI(a).replace(b,Cc),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Cc(a){a=a.charCodeAt(0);return \"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var wc=/[#\\/\\?@]/g,yc=/[#\\?:]/g,xc=/[#\\?]/g,Bc=/[#\\?@]/g,zc=/#/g;function sc(a,b){this.h=this.g=null;this.i=a||null;this.j=!!b;}\nfunction U(a){a.g||(a.g=new Map,a.h=0,a.i&&pc(a.i,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c);}));}h=sc.prototype;h.add=function(a,b){U(this);this.i=null;a=V(this,a);var c=this.g.get(a);c||this.g.set(a,c=[]);c.push(b);this.h+=1;return this};function Dc(a,b){U(a);b=V(a,b);a.g.has(b)&&(a.i=null,a.h-=a.g.get(b).length,a.g.delete(b));}function Ec(a,b){U(a);b=V(a,b);return a.g.has(b)}\nh.forEach=function(a,b){U(this);this.g.forEach(function(c,d){c.forEach(function(e){a.call(b,e,d,this);},this);},this);};h.na=function(){U(this);const a=Array.from(this.g.values()),b=Array.from(this.g.keys()),c=[];for(let d=0;d{d.abort();W(c,\"TestPingServer: timeout\",!1,b);},1E4);fetch(a,{signal:d.signal}).then(f=>{clearTimeout(e);f.ok?W(c,\"TestPingServer: ok\",!0,b):W(c,\"TestPingServer: server error\",!1,b);}).catch(()=>{clearTimeout(e);W(c,\"TestPingServer: error\",!1,b);});}function W(a,b,c,d,e){try{e&&(e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null),d(c);}catch(f){}}function Hc(){this.g=new jb;}function Ic(a,b,c){const d=c||\"\";try{nc(a,function(e,f){let g=e;n(e)&&(g=hb(e));b.push(d+f+\"=\"+encodeURIComponent(g));});}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}}function Jc(a){this.l=a.Ub||null;this.j=a.eb||!1;}r(Jc,kb);Jc.prototype.g=function(){return new Kc(this.l,this.j)};Jc.prototype.i=function(a){return function(){return a}}({});function Kc(a,b){E.call(this);this.D=a;this.o=b;this.m=void 0;this.status=this.readyState=0;this.responseType=this.responseText=this.response=this.statusText=\"\";this.onreadystatechange=null;this.u=new Headers;this.h=null;this.B=\"GET\";this.A=\"\";this.g=!1;this.v=this.j=this.l=null;}r(Kc,E);h=Kc.prototype;\nh.open=function(a,b){if(0!=this.readyState)throw this.abort(),Error(\"Error reopening a connection\");this.B=a;this.A=b;this.readyState=1;Lc(this);};h.send=function(a){if(1!=this.readyState)throw this.abort(),Error(\"need to call open() first. \");this.g=!0;const b={headers:this.u,method:this.B,credentials:this.m,cache:void 0};a&&(b.body=a);(this.D||k).fetch(new Request(this.A,b)).then(this.Sa.bind(this),this.ga.bind(this));};\nh.abort=function(){this.response=this.responseText=\"\";this.u=new Headers;this.status=0;this.j&&this.j.cancel(\"Request was aborted.\").catch(()=>{});1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Mc(this));this.readyState=0;};\nh.Sa=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,Lc(this)),this.g&&(this.readyState=3,Lc(this),this.g)))if(\"arraybuffer\"===this.responseType)a.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(\"undefined\"!==typeof k.ReadableStream&&\"body\"in a){this.j=a.body.getReader();if(this.o){if(this.responseType)throw Error('responseType must be empty for \"streamBinaryChunks\" mode responses.');this.response=\n[];}else this.response=this.responseText=\"\",this.v=new TextDecoder;Nc(this);}else a.text().then(this.Ra.bind(this),this.ga.bind(this));};function Nc(a){a.j.read().then(a.Pa.bind(a)).catch(a.ga.bind(a));}h.Pa=function(a){if(this.g){if(this.o&&a.value)this.response.push(a.value);else if(!this.o){var b=a.value?a.value:new Uint8Array(0);if(b=this.v.decode(b,{stream:!a.done}))this.response=this.responseText+=b;}a.done?Mc(this):Lc(this);3==this.readyState&&Nc(this);}};\nh.Ra=function(a){this.g&&(this.response=this.responseText=a,Mc(this));};h.Qa=function(a){this.g&&(this.response=a,Mc(this));};h.ga=function(){this.g&&Mc(this);};function Mc(a){a.readyState=4;a.l=null;a.j=null;a.v=null;Lc(a);}h.setRequestHeader=function(a,b){this.u.append(a,b);};h.getResponseHeader=function(a){return this.h?this.h.get(a.toLowerCase())||\"\":\"\"};\nh.getAllResponseHeaders=function(){if(!this.h)return \"\";const a=[],b=this.h.entries();for(var c=b.next();!c.done;)c=c.value,a.push(c[0]+\": \"+c[1]),c=b.next();return a.join(\"\\r\\n\")};function Lc(a){a.onreadystatechange&&a.onreadystatechange.call(a);}Object.defineProperty(Kc.prototype,\"withCredentials\",{get:function(){return \"include\"===this.m},set:function(a){this.m=a?\"include\":\"same-origin\";}});function Oc(a){let b=\"\";qa(a,function(c,d){b+=d;b+=\":\";b+=c;b+=\"\\r\\n\";});return b}function Pc(a,b,c){a:{for(d in c){var d=!1;break a}d=!0;}d||(c=Oc(c),\"string\"===typeof a?(null!=c&&encodeURIComponent(String(c))):S(a,b,c));}function X(a){E.call(this);this.headers=new Map;this.o=a||null;this.h=!1;this.v=this.g=null;this.D=\"\";this.m=0;this.l=\"\";this.j=this.B=this.u=this.A=!1;this.I=null;this.H=\"\";this.J=!1;}r(X,E);var Qc=/^https?$/i,Rc=[\"POST\",\"PUT\"];h=X.prototype;h.Ha=function(a){this.J=a;};\nh.ea=function(a,b,c,d){if(this.g)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.D+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.D=a;this.l=\"\";this.m=0;this.A=!1;this.h=!0;this.g=this.o?this.o.g():Cb.g();this.v=this.o?lb(this.o):lb(Cb);this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(b,String(a),!0),this.B=!1;}catch(f){Sc(this,f);return}a=c||\"\";c=new Map(this.headers);if(d)if(Object.getPrototypeOf(d)===Object.prototype)for(var e in d)c.set(e,d[e]);else if(\"function\"===\ntypeof d.keys&&\"function\"===typeof d.get)for(const f of d.keys())c.set(f,d.get(f));else throw Error(\"Unknown input type for opt_headers: \"+String(d));d=Array.from(c.keys()).find(f=>\"content-type\"==f.toLowerCase());e=k.FormData&&a instanceof k.FormData;!(0<=Array.prototype.indexOf.call(Rc,b,void 0))||d||e||c.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");for(const [f,g]of c)this.g.setRequestHeader(f,g);this.H&&(this.g.responseType=this.H);\"withCredentials\"in this.g&&this.g.withCredentials!==\nthis.J&&(this.g.withCredentials=this.J);try{Tc(this),this.u=!0,this.g.send(a),this.u=!1;}catch(f){Sc(this,f);}};function Sc(a,b){a.h=!1;a.g&&(a.j=!0,a.g.abort(),a.j=!1);a.l=b;a.m=5;Uc(a);Vc(a);}function Uc(a){a.A||(a.A=!0,F(a,\"complete\"),F(a,\"error\"));}h.abort=function(a){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=a||7,F(this,\"complete\"),F(this,\"abort\"),Vc(this));};h.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Vc(this,!0));X.aa.N.call(this);};\nh.Ea=function(){this.s||(this.B||this.u||this.j?Wc(this):this.bb());};h.bb=function(){Wc(this);};\nfunction Wc(a){if(a.h&&\"undefined\"!=typeof fa&&(!a.v[1]||4!=P(a)||2!=a.Z()))if(a.u&&4==P(a))bb(a.Ea,0,a);else if(F(a,\"readystatechange\"),4==P(a)){a.h=!1;try{const g=a.Z();a:switch(g){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var b=!0;break a;default:b=!1;}var c;if(!(c=b)){var d;if(d=0===g){var e=String(a.D).match(oc)[1]||null;!e&&k.self&&k.self.location&&(e=k.self.location.protocol.slice(0,-1));d=!Qc.test(e?e.toLowerCase():\"\");}c=d;}if(c)F(a,\"complete\"),F(a,\"success\");else {a.m=\n6;try{var f=2{}:null;a.g=null;a.v=null;b||F(a,\"ready\");try{c.onreadystatechange=d;}catch(e){}}}function Tc(a){a.I&&(k.clearTimeout(a.I),a.I=null);}h.isActive=function(){return !!this.g};function P(a){return a.g?a.g.readyState:0}h.Z=function(){try{return 2=a.h.j-(a.s?1:0))return !1;if(a.s)return a.i=b.D.concat(a.i),!0;if(1==a.G||2==a.G||a.B>=(a.Va?0:a.Wa))return !1;a.s=ub(p(a.Ga,a,b),cd(a,a.B));a.B++;return !0}\nh.Ga=function(a){if(this.s)if(this.s=null,1==this.G){if(!a){this.U=Math.floor(1E5*Math.random());a=this.U++;const e=new M(this,this.j,a);let f=this.o;this.S&&(f?(f=sa(f),ua(f,this.S)):f=this.S);null!==this.m||this.O||(e.H=f,f=null);if(this.P)a:{var b=0;for(var c=0;cl)f=Math.max(0,e[q].g-100),m=!1;else try{Ic(v,g,\"req\"+l+\"_\");}catch(w){d&&d(v);}}if(m){d=g.join(\"&\");break a}}}a=a.i.splice(0,c);b.D=a;return d}function ec(a){if(!a.g&&!a.u){a.Y=1;var b=a.Fa;x||Ea();y||(x(),y=!0);za.add(b,a);a.v=0;}}\nfunction $b(a){if(a.g||a.u||3<=a.v)return !1;a.Y++;a.u=ub(p(a.Fa,a),cd(a,a.v));a.v++;return !0}h.Fa=function(){this.u=null;fd(this);if(this.ba&&!(this.M||null==this.g||0>=this.R)){var a=2*this.R;this.j.info(\"BP detection timer enabled: \"+a);this.A=ub(p(this.ab,this),a);}};h.ab=function(){this.A&&(this.A=null,this.j.info(\"BP detection timeout reached.\"),this.j.info(\"Buffering proxy detected and switch to long-polling!\"),this.F=!1,this.M=!0,K(10),Zb(this),fd(this));};\nfunction Tb(a){null!=a.A&&(k.clearTimeout(a.A),a.A=null);}function fd(a){a.g=new M(a,a.j,\"rpc\",a.Y);null===a.m&&(a.g.H=a.o);a.g.O=0;var b=N(a.qa);S(b,\"RID\",\"rpc\");S(b,\"SID\",a.K);S(b,\"AID\",a.T);S(b,\"CI\",a.F?\"0\":\"1\");!a.F&&a.ja&&S(b,\"TO\",a.ja);S(b,\"TYPE\",\"xmlhttp\");$c(a,b);a.m&&a.o&&Pc(b,a.m,a.o);a.L&&(a.g.I=a.L);var c=a.g;a=a.ia;c.L=1;c.v=Ib(N(b));c.m=null;c.P=!0;Jb(c,a);}h.Za=function(){null!=this.C&&(this.C=null,Zb(this),$b(this),K(19));};function Yb(a){null!=a.C&&(k.clearTimeout(a.C),a.C=null);}\nfunction Ub(a,b){var c=null;if(a.g==b){Yb(a);Tb(a);a.g=null;var d=2;}else if(Xb(a.h,b))c=b.D,dc(a.h,b),d=1;else return;if(0!=a.G)if(b.o)if(1==d){c=b.m?b.m.length:0;b=Date.now()-b.F;var e=a.B;d=qb();F(d,new tb(d,c));fc(a);}else ec(a);else if(e=b.s,3==e||0==e&&0\n *

  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n * \n */ function setLogLevel(e) {\n b.setLogLevel(e);\n}\n\nfunction __PRIVATE_logDebug(e, ...t) {\n if (b.logLevel <= LogLevel.DEBUG) {\n const n = t.map(__PRIVATE_argToString);\n b.debug(`Firestore (${S}): ${e}`, ...n);\n }\n}\n\nfunction __PRIVATE_logError(e, ...t) {\n if (b.logLevel <= LogLevel.ERROR) {\n const n = t.map(__PRIVATE_argToString);\n b.error(`Firestore (${S}): ${e}`, ...n);\n }\n}\n\n/**\n * @internal\n */ function __PRIVATE_logWarn(e, ...t) {\n if (b.logLevel <= LogLevel.WARN) {\n const n = t.map(__PRIVATE_argToString);\n b.warn(`Firestore (${S}): ${e}`, ...n);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */ function __PRIVATE_argToString(e) {\n if (\"string\" == typeof e) return e;\n try {\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 /** Formats an object as a JSON string, suitable for logging. */\n return function __PRIVATE_formatJSON(e) {\n return JSON.stringify(e);\n }(e);\n } catch (t) {\n // Converting to JSON failed, just log the object directly\n return e;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */ function fail(e = \"Unexpected state\") {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const t = `FIRESTORE (${S}) INTERNAL ASSERTION FAILED: ` + e;\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw __PRIVATE_logError(t), new Error(t);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */ function __PRIVATE_hardAssert(e, t) {\n e || fail();\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */ function __PRIVATE_debugAssert(e, t) {\n e || fail();\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */ function __PRIVATE_debugCast(e, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nt) {\n return e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const D = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: \"ok\",\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: \"cancelled\",\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: \"unknown\",\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: \"invalid-argument\",\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: \"deadline-exceeded\",\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: \"not-found\",\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: \"already-exists\",\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller cannot be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: \"permission-denied\",\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: \"unauthenticated\",\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: \"resource-exhausted\",\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: \"failed-precondition\",\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: \"aborted\",\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: \"out-of-range\",\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: \"unimplemented\",\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: \"internal\",\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: \"unavailable\",\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: \"data-loss\"\n};\n\n/** An error returned by a Firestore operation. */ class FirestoreError extends FirebaseError {\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n e, \n /**\n * A custom error description.\n */\n t) {\n super(e, t), this.code = e, this.message = t, \n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_Deferred {\n constructor() {\n this.promise = new Promise(((e, t) => {\n this.resolve = e, this.reject = t;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_OAuthToken {\n constructor(e, t) {\n this.user = t, this.type = \"OAuth\", this.headers = new Map, this.headers.set(\"Authorization\", `Bearer ${e}`);\n }\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */ class __PRIVATE_EmptyAuthCredentialsProvider {\n getToken() {\n return Promise.resolve(null);\n }\n invalidateToken() {}\n start(e, t) {\n // Fire with initial user.\n e.enqueueRetryable((() => t(User.UNAUTHENTICATED)));\n }\n shutdown() {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */ class __PRIVATE_EmulatorAuthCredentialsProvider {\n constructor(e) {\n this.token = e, \n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n this.changeListener = null;\n }\n getToken() {\n return Promise.resolve(this.token);\n }\n invalidateToken() {}\n start(e, t) {\n this.changeListener = t, \n // Fire with initial user.\n e.enqueueRetryable((() => t(this.token.user)));\n }\n shutdown() {\n this.changeListener = null;\n }\n}\n\nclass __PRIVATE_FirebaseAuthCredentialsProvider {\n constructor(e) {\n this.t = e, \n /** Tracks the current User. */\n this.currentUser = User.UNAUTHENTICATED, \n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n this.i = 0, this.forceRefresh = !1, this.auth = null;\n }\n start(e, t) {\n __PRIVATE_hardAssert(void 0 === this.o);\n let n = this.i;\n // A change listener that prevents double-firing for the same token change.\n const __PRIVATE_guardedChangeListener = e => this.i !== n ? (n = this.i, \n t(e)) : Promise.resolve();\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let r = new __PRIVATE_Deferred;\n this.o = () => {\n this.i++, this.currentUser = this.u(), r.resolve(), r = new __PRIVATE_Deferred, \n e.enqueueRetryable((() => __PRIVATE_guardedChangeListener(this.currentUser)));\n };\n const __PRIVATE_awaitNextToken = () => {\n const t = r;\n e.enqueueRetryable((async () => {\n await t.promise, await __PRIVATE_guardedChangeListener(this.currentUser);\n }));\n }, __PRIVATE_registerAuth = e => {\n __PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"Auth detected\"), this.auth = e, \n this.o && (this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken());\n };\n this.t.onInit((e => __PRIVATE_registerAuth(e))), \n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout((() => {\n if (!this.auth) {\n const e = this.t.getImmediate({\n optional: !0\n });\n e ? __PRIVATE_registerAuth(e) : (\n // If auth is still not available, proceed with `null` user\n __PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"Auth not yet detected\"), \n r.resolve(), r = new __PRIVATE_Deferred);\n }\n }), 0), __PRIVATE_awaitNextToken();\n }\n getToken() {\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const e = this.i, t = this.forceRefresh;\n return this.forceRefresh = !1, this.auth ? this.auth.getToken(t).then((t => \n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n this.i !== e ? (__PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"getToken aborted due to token change.\"), \n this.getToken()) : t ? (__PRIVATE_hardAssert(\"string\" == typeof t.accessToken), \n new __PRIVATE_OAuthToken(t.accessToken, this.currentUser)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.auth && this.o && this.auth.removeAuthTokenListener(this.o), this.o = void 0;\n }\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n u() {\n const e = this.auth && this.auth.getUid();\n return __PRIVATE_hardAssert(null === e || \"string\" == typeof e), new User(e);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */ class __PRIVATE_FirstPartyToken {\n constructor(e, t, n) {\n this.l = e, this.h = t, this.P = n, this.type = \"FirstParty\", this.user = User.FIRST_PARTY, \n this.I = new Map;\n }\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */ T() {\n return this.P ? this.P() : null;\n }\n get headers() {\n this.I.set(\"X-Goog-AuthUser\", this.l);\n // Use array notation to prevent minification\n const e = this.T();\n return e && this.I.set(\"Authorization\", e), this.h && this.I.set(\"X-Goog-Iam-Authorization-Token\", this.h), \n this.I;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */ class __PRIVATE_FirstPartyAuthCredentialsProvider {\n constructor(e, t, n) {\n this.l = e, this.h = t, this.P = n;\n }\n getToken() {\n return Promise.resolve(new __PRIVATE_FirstPartyToken(this.l, this.h, this.P));\n }\n start(e, t) {\n // Fire with initial uid.\n e.enqueueRetryable((() => t(User.FIRST_PARTY)));\n }\n shutdown() {}\n invalidateToken() {}\n}\n\nclass AppCheckToken {\n constructor(e) {\n this.value = e, this.type = \"AppCheck\", this.headers = new Map, e && e.length > 0 && this.headers.set(\"x-firebase-appcheck\", this.value);\n }\n}\n\nclass __PRIVATE_FirebaseAppCheckTokenProvider {\n constructor(e) {\n this.A = e, this.forceRefresh = !1, this.appCheck = null, this.R = null;\n }\n start(e, t) {\n __PRIVATE_hardAssert(void 0 === this.o);\n const onTokenChanged = e => {\n null != e.error && __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", `Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);\n const n = e.token !== this.R;\n return this.R = e.token, __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", `Received ${n ? \"new\" : \"existing\"} token.`), \n n ? t(e.token) : Promise.resolve();\n };\n this.o = t => {\n e.enqueueRetryable((() => onTokenChanged(t)));\n };\n const __PRIVATE_registerAppCheck = e => {\n __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", \"AppCheck detected\"), this.appCheck = e, \n this.o && this.appCheck.addTokenListener(this.o);\n };\n this.A.onInit((e => __PRIVATE_registerAppCheck(e))), \n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout((() => {\n if (!this.appCheck) {\n const e = this.A.getImmediate({\n optional: !0\n });\n e ? __PRIVATE_registerAppCheck(e) : \n // If AppCheck is still not available, proceed without it.\n __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", \"AppCheck not yet detected\");\n }\n }), 0);\n }\n getToken() {\n const e = this.forceRefresh;\n return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(e).then((e => e ? (__PRIVATE_hardAssert(\"string\" == typeof e.token), \n this.R = e.token, new AppCheckToken(e.token)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.appCheck && this.o && this.appCheck.removeTokenListener(this.o), this.o = void 0;\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */ class __PRIVATE_EmptyAppCheckTokenProvider {\n getToken() {\n return Promise.resolve(new AppCheckToken(\"\"));\n }\n invalidateToken() {}\n start(e, t) {}\n shutdown() {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\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 * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nfunction __PRIVATE_randomBytes(e) {\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const t = \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n \"undefined\" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(e);\n if (t && \"function\" == typeof t.getRandomValues) t.getRandomValues(n); else \n // Falls back to Math.random\n for (let t = 0; t < e; t++) n[t] = Math.floor(256 * Math.random());\n return n;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */ class __PRIVATE_AutoId {\n static newId() {\n // Alphanumeric characters\n const e = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", t = Math.floor(256 / e.length) * e.length;\n // The largest byte value that is a multiple of `char.length`.\n let n = \"\";\n for (;n.length < 20; ) {\n const r = __PRIVATE_randomBytes(40);\n for (let i = 0; i < r.length; ++i) \n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n n.length < 20 && r[i] < t && (n += e.charAt(r[i] % e.length));\n }\n return n;\n }\n}\n\nfunction __PRIVATE_primitiveComparator(e, t) {\n return e < t ? -1 : e > t ? 1 : 0;\n}\n\n/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(e, t, n) {\n return e.length === t.length && e.every(((e, r) => n(e, t[r])));\n}\n\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */ function __PRIVATE_immediateSuccessor(e) {\n // Return the input string, with an additional NUL byte appended.\n return e + \"\\0\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nclass Timestamp {\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n e, \n /**\n * The fractions of a second at nanosecond resolution.*\n */\n t) {\n if (this.seconds = e, this.nanoseconds = t, t < 0) throw new FirestoreError(D.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + t);\n if (t >= 1e9) throw new FirestoreError(D.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + t);\n if (e < -62135596800) throw new FirestoreError(D.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + e);\n // This will break in the year 10,000.\n if (e >= 253402300800) throw new FirestoreError(D.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + e);\n }\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */ static now() {\n return Timestamp.fromMillis(Date.now());\n }\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */ static fromDate(e) {\n return Timestamp.fromMillis(e.getTime());\n }\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */ static fromMillis(e) {\n const t = Math.floor(e / 1e3), n = Math.floor(1e6 * (e - 1e3 * t));\n return new Timestamp(t, n);\n }\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */ toDate() {\n return new Date(this.toMillis());\n }\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */ toMillis() {\n return 1e3 * this.seconds + this.nanoseconds / 1e6;\n }\n _compareTo(e) {\n return this.seconds === e.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e.seconds);\n }\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */ isEqual(e) {\n return e.seconds === this.seconds && e.nanoseconds === this.nanoseconds;\n }\n /** Returns a textual representation of this `Timestamp`. */ toString() {\n return \"Timestamp(seconds=\" + this.seconds + \", nanoseconds=\" + this.nanoseconds + \")\";\n }\n /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {\n return {\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */ valueOf() {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexicographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexicographical ordering.\n const e = this.seconds - -62135596800;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n return String(e).padStart(12, \"0\") + \".\" + String(this.nanoseconds).padStart(9, \"0\");\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */ class SnapshotVersion {\n constructor(e) {\n this.timestamp = e;\n }\n static fromTimestamp(e) {\n return new SnapshotVersion(e);\n }\n static min() {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n static max() {\n return new SnapshotVersion(new Timestamp(253402300799, 999999999));\n }\n compareTo(e) {\n return this.timestamp._compareTo(e.timestamp);\n }\n isEqual(e) {\n return this.timestamp.isEqual(e.timestamp);\n }\n /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {\n // Convert to microseconds.\n return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;\n }\n toString() {\n return \"SnapshotVersion(\" + this.timestamp.toString() + \")\";\n }\n toTimestamp() {\n return this.timestamp;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Path represents an ordered sequence of string segments.\n */\nclass BasePath {\n constructor(e, t, n) {\n void 0 === t ? t = 0 : t > e.length && fail(), void 0 === n ? n = e.length - t : n > e.length - t && fail(), \n this.segments = e, this.offset = t, this.len = n;\n }\n get length() {\n return this.len;\n }\n isEqual(e) {\n return 0 === BasePath.comparator(this, e);\n }\n child(e) {\n const t = this.segments.slice(this.offset, this.limit());\n return e instanceof BasePath ? e.forEach((e => {\n t.push(e);\n })) : t.push(e), this.construct(t);\n }\n /** The index of one past the last segment of the path. */ limit() {\n return this.offset + this.length;\n }\n popFirst(e) {\n return e = void 0 === e ? 1 : e, this.construct(this.segments, this.offset + e, this.length - e);\n }\n popLast() {\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n firstSegment() {\n return this.segments[this.offset];\n }\n lastSegment() {\n return this.get(this.length - 1);\n }\n get(e) {\n return this.segments[this.offset + e];\n }\n isEmpty() {\n return 0 === this.length;\n }\n isPrefixOf(e) {\n if (e.length < this.length) return !1;\n for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1;\n return !0;\n }\n isImmediateParentOf(e) {\n if (this.length + 1 !== e.length) return !1;\n for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1;\n return !0;\n }\n forEach(e) {\n for (let t = this.offset, n = this.limit(); t < n; t++) e(this.segments[t]);\n }\n toArray() {\n return this.segments.slice(this.offset, this.limit());\n }\n static comparator(e, t) {\n const n = Math.min(e.length, t.length);\n for (let r = 0; r < n; r++) {\n const n = e.get(r), i = t.get(r);\n if (n < i) return -1;\n if (n > i) return 1;\n }\n return e.length < t.length ? -1 : e.length > t.length ? 1 : 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */ class ResourcePath extends BasePath {\n construct(e, t, n) {\n return new ResourcePath(e, t, n);\n }\n canonicalString() {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n return this.toArray().join(\"/\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */ toUriEncodedString() {\n return this.toArray().map(encodeURIComponent).join(\"/\");\n }\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */ static fromString(...e) {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n const t = [];\n for (const n of e) {\n if (n.indexOf(\"//\") >= 0) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);\n // Strip leading and trailing slashed.\n t.push(...n.split(\"/\").filter((e => e.length > 0)));\n }\n return new ResourcePath(t);\n }\n static emptyPath() {\n return new ResourcePath([]);\n }\n}\n\nconst v = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */ class FieldPath$1 extends BasePath {\n construct(e, t, n) {\n return new FieldPath$1(e, t, n);\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */ static isValidIdentifier(e) {\n return v.test(e);\n }\n canonicalString() {\n return this.toArray().map((e => (e = e.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\"), \n FieldPath$1.isValidIdentifier(e) || (e = \"`\" + e + \"`\"), e))).join(\".\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Returns true if this field references the key of a document.\n */ isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }\n /**\n * The field designating the key of a document.\n */ static keyField() {\n return new FieldPath$1([ \"__name__\" ]);\n }\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */ static fromServerFormat(e) {\n const t = [];\n let n = \"\", r = 0;\n const __PRIVATE_addCurrentSegment = () => {\n if (0 === n.length) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);\n t.push(n), n = \"\";\n };\n let i = !1;\n for (;r < e.length; ) {\n const t = e[r];\n if (\"\\\\\" === t) {\n if (r + 1 === e.length) throw new FirestoreError(D.INVALID_ARGUMENT, \"Path has trailing escape character: \" + e);\n const t = e[r + 1];\n if (\"\\\\\" !== t && \".\" !== t && \"`\" !== t) throw new FirestoreError(D.INVALID_ARGUMENT, \"Path has invalid escape sequence: \" + e);\n n += t, r += 2;\n } else \"`\" === t ? (i = !i, r++) : \".\" !== t || i ? (n += t, r++) : (__PRIVATE_addCurrentSegment(), \n r++);\n }\n if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(D.INVALID_ARGUMENT, \"Unterminated ` in path: \" + e);\n return new FieldPath$1(t);\n }\n static emptyPath() {\n return new FieldPath$1([]);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */ class DocumentKey {\n constructor(e) {\n this.path = e;\n }\n static fromPath(e) {\n return new DocumentKey(ResourcePath.fromString(e));\n }\n static fromName(e) {\n return new DocumentKey(ResourcePath.fromString(e).popFirst(5));\n }\n static empty() {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n get collectionGroup() {\n return this.path.popLast().lastSegment();\n }\n /** Returns true if the document is in the specified collectionId. */ hasCollectionId(e) {\n return this.path.length >= 2 && this.path.get(this.path.length - 2) === e;\n }\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {\n return this.path.get(this.path.length - 2);\n }\n /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {\n return this.path.popLast();\n }\n isEqual(e) {\n return null !== e && 0 === ResourcePath.comparator(this.path, e.path);\n }\n toString() {\n return this.path.toString();\n }\n static comparator(e, t) {\n return ResourcePath.comparator(e.path, t.path);\n }\n static isDocumentKey(e) {\n return e.length % 2 == 0;\n }\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */ static fromSegments(e) {\n return new DocumentKey(new ResourcePath(e.slice()));\n }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nclass FieldIndex {\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n e, \n /** The collection ID this index applies to. */\n t, \n /** The field segments for this index. */\n n, \n /** Shows how up-to-date the index is for the current user. */\n r) {\n this.indexId = e, this.collectionGroup = t, this.fields = n, this.indexState = r;\n }\n}\n\n/** An ID for an index that has not yet been added to persistence. */\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nfunction __PRIVATE_fieldIndexGetArraySegment(e) {\n return e.fields.find((e => 2 /* IndexKind.CONTAINS */ === e.kind));\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */ function __PRIVATE_fieldIndexGetDirectionalSegments(e) {\n return e.fields.filter((e => 2 /* IndexKind.CONTAINS */ !== e.kind));\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nfunction __PRIVATE_fieldIndexSemanticComparator(e, t) {\n let n = __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);\n if (0 !== n) return n;\n for (let r = 0; r < Math.min(e.fields.length, t.fields.length); ++r) if (n = __PRIVATE_indexSegmentComparator(e.fields[r], t.fields[r]), \n 0 !== n) return n;\n return __PRIVATE_primitiveComparator(e.fields.length, t.fields.length);\n}\n\n/** Returns a debug representation of the field index */ FieldIndex.UNKNOWN_ID = -1;\n\n/** An index component consisting of field path and index type. */\nclass IndexSegment {\n constructor(\n /** The field path of the component. */\n e, \n /** The fields sorting order. */\n t) {\n this.fieldPath = e, this.kind = t;\n }\n}\n\nfunction __PRIVATE_indexSegmentComparator(e, t) {\n const n = FieldPath$1.comparator(e.fieldPath, t.fieldPath);\n return 0 !== n ? n : __PRIVATE_primitiveComparator(e.kind, t.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */ class IndexState {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n e, \n /** The the latest indexed read time, document and batch id. */\n t) {\n this.sequenceNumber = e, this.offset = t;\n }\n /** The state of an index that has not yet been backfilled. */ static empty() {\n return new IndexState(0, IndexOffset.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */ function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e, t) {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const n = e.toTimestamp().seconds, r = e.toTimestamp().nanoseconds + 1, i = SnapshotVersion.fromTimestamp(1e9 === r ? new Timestamp(n + 1, 0) : new Timestamp(n, r));\n return new IndexOffset(i, DocumentKey.empty(), t);\n}\n\n/** Creates a new offset based on the provided document. */ function __PRIVATE_newIndexOffsetFromDocument(e) {\n return new IndexOffset(e.readTime, e.key, -1);\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */ class IndexOffset {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n e, \n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n t, \n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n n) {\n this.readTime = e, this.documentKey = t, this.largestBatchId = n;\n }\n /** Returns an offset that sorts before all regular offsets. */ static min() {\n return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), -1);\n }\n /** Returns an offset that sorts after all regular offsets. */ static max() {\n return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), -1);\n }\n}\n\nfunction __PRIVATE_indexOffsetComparator(e, t) {\n let n = e.readTime.compareTo(t.readTime);\n return 0 !== n ? n : (n = DocumentKey.comparator(e.documentKey, t.documentKey), \n 0 !== n ? n : __PRIVATE_primitiveComparator(e.largestBatchId, t.largestBatchId));\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 */ const C = \"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.\";\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */ class PersistenceTransaction {\n constructor() {\n this.onCommittedListeners = [];\n }\n addOnCommittedListener(e) {\n this.onCommittedListeners.push(e);\n }\n raiseOnCommittedEvent() {\n this.onCommittedListeners.forEach((e => e()));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */ async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e) {\n if (e.code !== D.FAILED_PRECONDITION || e.message !== C) throw e;\n __PRIVATE_logDebug(\"LocalStore\", \"Unexpectedly lost primary lease\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */ class PersistencePromise {\n constructor(e) {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n this.nextCallback = null, this.catchCallback = null, \n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = void 0, this.error = void 0, this.isDone = !1, \n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = !1, e((e => {\n this.isDone = !0, this.result = e, this.nextCallback && \n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(e);\n }), (e => {\n this.isDone = !0, this.error = e, this.catchCallback && this.catchCallback(e);\n }));\n }\n catch(e) {\n return this.next(void 0, e);\n }\n next(e, t) {\n return this.callbackAttached && fail(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(t, this.error) : this.wrapSuccess(e, this.result) : new PersistencePromise(((n, r) => {\n this.nextCallback = t => {\n this.wrapSuccess(e, t).next(n, r);\n }, this.catchCallback = e => {\n this.wrapFailure(t, e).next(n, r);\n };\n }));\n }\n toPromise() {\n return new Promise(((e, t) => {\n this.next(e, t);\n }));\n }\n wrapUserFunction(e) {\n try {\n const t = e();\n return t instanceof PersistencePromise ? t : PersistencePromise.resolve(t);\n } catch (e) {\n return PersistencePromise.reject(e);\n }\n }\n wrapSuccess(e, t) {\n return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.resolve(t);\n }\n wrapFailure(e, t) {\n return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.reject(t);\n }\n static resolve(e) {\n return new PersistencePromise(((t, n) => {\n t(e);\n }));\n }\n static reject(e) {\n return new PersistencePromise(((t, n) => {\n n(e);\n }));\n }\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n e) {\n return new PersistencePromise(((t, n) => {\n let r = 0, i = 0, s = !1;\n e.forEach((e => {\n ++r, e.next((() => {\n ++i, s && i === r && t();\n }), (e => n(e)));\n })), s = !0, i === r && t();\n }));\n }\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */ static or(e) {\n let t = PersistencePromise.resolve(!1);\n for (const n of e) t = t.next((e => e ? PersistencePromise.resolve(e) : n()));\n return t;\n }\n static forEach(e, t) {\n const n = [];\n return e.forEach(((e, r) => {\n n.push(t.call(this, e, r));\n })), this.waitFor(n);\n }\n /**\n * Concurrently map all array elements through asynchronous function.\n */ static mapArray(e, t) {\n return new PersistencePromise(((n, r) => {\n const i = e.length, s = new Array(i);\n let o = 0;\n for (let _ = 0; _ < i; _++) {\n const a = _;\n t(e[a]).next((e => {\n s[a] = e, ++o, o === i && n(s);\n }), (e => r(e)));\n }\n }));\n }\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */ static doWhile(e, t) {\n return new PersistencePromise(((n, r) => {\n const process = () => {\n !0 === e() ? t().next((() => {\n process();\n }), r) : n();\n };\n process();\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nclass __PRIVATE_SimpleDbTransaction {\n constructor(e, t) {\n this.action = e, this.transaction = t, this.aborted = !1, \n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n this.V = new __PRIVATE_Deferred, this.transaction.oncomplete = () => {\n this.V.resolve();\n }, this.transaction.onabort = () => {\n t.error ? this.V.reject(new __PRIVATE_IndexedDbTransactionError(e, t.error)) : this.V.resolve();\n }, this.transaction.onerror = t => {\n const n = __PRIVATE_checkForAndReportiOSError(t.target.error);\n this.V.reject(new __PRIVATE_IndexedDbTransactionError(e, n));\n };\n }\n static open(e, t, n, r) {\n try {\n return new __PRIVATE_SimpleDbTransaction(t, e.transaction(r, n));\n } catch (e) {\n throw new __PRIVATE_IndexedDbTransactionError(t, e);\n }\n }\n get m() {\n return this.V.promise;\n }\n abort(e) {\n e && this.V.reject(e), this.aborted || (__PRIVATE_logDebug(\"SimpleDb\", \"Aborting transaction:\", e ? e.message : \"Client-initiated abort\"), \n this.aborted = !0, this.transaction.abort());\n }\n g() {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = this.transaction;\n this.aborted || \"function\" != typeof e.commit || e.commit();\n }\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */ store(e) {\n const t = this.transaction.objectStore(e);\n return new __PRIVATE_SimpleDbStore(t);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */ class __PRIVATE_SimpleDb {\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(e, t, n) {\n this.name = e, this.version = t, this.p = n;\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n 12.2 === __PRIVATE_SimpleDb.S(getUA()) && __PRIVATE_logError(\"Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.\");\n }\n /** Deletes the specified database. */ static delete(e) {\n return __PRIVATE_logDebug(\"SimpleDb\", \"Removing database:\", e), __PRIVATE_wrapRequest(window.indexedDB.deleteDatabase(e)).toPromise();\n }\n /** Returns true if IndexedDB is available in the current environment. */ static D() {\n if (!isIndexedDBAvailable()) return !1;\n if (__PRIVATE_SimpleDb.v()) return !0;\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n // Check the UA string to find out the browser.\n const e = getUA(), t = __PRIVATE_SimpleDb.S(e), n = 0 < t && t < 10, r = __PRIVATE_getAndroidVersion(e), i = 0 < r && r < 4.5;\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n // iOS Safari: Disable for users running iOS version < 10.\n return !(e.indexOf(\"MSIE \") > 0 || e.indexOf(\"Trident/\") > 0 || e.indexOf(\"Edge/\") > 0 || n || i);\n }\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */ static v() {\n var e;\n return \"undefined\" != typeof process && \"YES\" === (null === (e = process.__PRIVATE_env) || void 0 === e ? void 0 : e.C);\n }\n /** Helper to get a typed SimpleDbStore from a transaction. */ static F(e, t) {\n return e.store(t);\n }\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static S(e) {\n const t = e.match(/i(?:phone|pad|pod) os ([\\d_]+)/i), n = t ? t[1].split(\"_\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */ async M(e) {\n return this.db || (__PRIVATE_logDebug(\"SimpleDb\", \"Opening database:\", this.name), \n this.db = await new Promise(((t, n) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const r = indexedDB.open(this.name, this.version);\n r.onsuccess = e => {\n const n = e.target.result;\n t(n);\n }, r.onblocked = () => {\n n(new __PRIVATE_IndexedDbTransactionError(e, \"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.\"));\n }, r.onerror = t => {\n const r = t.target.error;\n \"VersionError\" === r.name ? n(new FirestoreError(D.FAILED_PRECONDITION, \"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.\")) : \"InvalidStateError\" === r.name ? n(new FirestoreError(D.FAILED_PRECONDITION, \"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: \" + r)) : n(new __PRIVATE_IndexedDbTransactionError(e, r));\n }, r.onupgradeneeded = e => {\n __PRIVATE_logDebug(\"SimpleDb\", 'Database \"' + this.name + '\" requires upgrade from version:', e.oldVersion);\n const t = e.target.result;\n this.p.O(t, r.transaction, e.oldVersion, this.version).next((() => {\n __PRIVATE_logDebug(\"SimpleDb\", \"Database upgrade to version \" + this.version + \" complete\");\n }));\n };\n }))), this.N && (this.db.onversionchange = e => this.N(e)), this.db;\n }\n L(e) {\n this.N = e, this.db && (this.db.onversionchange = t => e(t));\n }\n async runTransaction(e, t, n, r) {\n const i = \"readonly\" === t;\n let s = 0;\n for (;;) {\n ++s;\n try {\n this.db = await this.M(e);\n const t = __PRIVATE_SimpleDbTransaction.open(this.db, e, i ? \"readonly\" : \"readwrite\", n), s = r(t).next((e => (t.g(), \n e))).catch((e => (\n // Abort the transaction if there was an error.\n t.abort(e), PersistencePromise.reject(e)))).toPromise();\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n return s.catch((() => {})), \n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await t.m, s;\n } catch (e) {\n const t = e, n = \"FirebaseError\" !== t.name && s < 3;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n if (__PRIVATE_logDebug(\"SimpleDb\", \"Transaction failed with error:\", t.message, \"Retrying:\", n), \n this.close(), !n) return Promise.reject(t);\n }\n }\n }\n close() {\n this.db && this.db.close(), this.db = void 0;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */ function __PRIVATE_getAndroidVersion(e) {\n const t = e.match(/Android ([\\d.]+)/i), n = t ? t[1].split(\".\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */ class __PRIVATE_IterationController {\n constructor(e) {\n this.B = e, this.k = !1, this.q = null;\n }\n get isDone() {\n return this.k;\n }\n get K() {\n return this.q;\n }\n set cursor(e) {\n this.B = e;\n }\n /**\n * This function can be called to stop iteration at any point.\n */ done() {\n this.k = !0;\n }\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */ $(e) {\n this.q = e;\n }\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */ delete() {\n return __PRIVATE_wrapRequest(this.B.delete());\n }\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */ class __PRIVATE_IndexedDbTransactionError extends FirestoreError {\n constructor(e, t) {\n super(D.UNAVAILABLE, `IndexedDB transaction '${e}' failed: ${t}`), this.name = \"IndexedDbTransactionError\";\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */ function __PRIVATE_isIndexedDbTransactionError(e) {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return \"IndexedDbTransactionError\" === e.name;\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */ class __PRIVATE_SimpleDbStore {\n constructor(e) {\n this.store = e;\n }\n put(e, t) {\n let n;\n return void 0 !== t ? (__PRIVATE_logDebug(\"SimpleDb\", \"PUT\", this.store.name, e, t), \n n = this.store.put(t, e)) : (__PRIVATE_logDebug(\"SimpleDb\", \"PUT\", this.store.name, \"\", e), \n n = this.store.put(e)), __PRIVATE_wrapRequest(n);\n }\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */ add(e) {\n __PRIVATE_logDebug(\"SimpleDb\", \"ADD\", this.store.name, e, e);\n return __PRIVATE_wrapRequest(this.store.add(e));\n }\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */ get(e) {\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return __PRIVATE_wrapRequest(this.store.get(e)).next((t => (\n // Normalize nonexistence to null.\n void 0 === t && (t = null), __PRIVATE_logDebug(\"SimpleDb\", \"GET\", this.store.name, e, t), \n t)));\n }\n delete(e) {\n __PRIVATE_logDebug(\"SimpleDb\", \"DELETE\", this.store.name, e);\n return __PRIVATE_wrapRequest(this.store.delete(e));\n }\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */ count() {\n __PRIVATE_logDebug(\"SimpleDb\", \"COUNT\", this.store.name);\n return __PRIVATE_wrapRequest(this.store.count());\n }\n U(e, t) {\n const n = this.options(e, t), r = n.index ? this.store.index(n.index) : this.store;\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n if (\"function\" == typeof r.getAll) {\n const e = r.getAll(n.range);\n return new PersistencePromise(((t, n) => {\n e.onerror = e => {\n n(e.target.error);\n }, e.onsuccess = e => {\n t(e.target.result);\n };\n }));\n }\n {\n const e = this.cursor(n), t = [];\n return this.W(e, ((e, n) => {\n t.push(n);\n })).next((() => t));\n }\n }\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */ G(e, t) {\n const n = this.store.getAll(e, null === t ? void 0 : t);\n return new PersistencePromise(((e, t) => {\n n.onerror = e => {\n t(e.target.error);\n }, n.onsuccess = t => {\n e(t.target.result);\n };\n }));\n }\n j(e, t) {\n __PRIVATE_logDebug(\"SimpleDb\", \"DELETE ALL\", this.store.name);\n const n = this.options(e, t);\n n.H = !1;\n const r = this.cursor(n);\n return this.W(r, ((e, t, n) => n.delete()));\n }\n J(e, t) {\n let n;\n t ? n = e : (n = {}, t = e);\n const r = this.cursor(n);\n return this.W(r, t);\n }\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */ Y(e) {\n const t = this.cursor({});\n return new PersistencePromise(((n, r) => {\n t.onerror = e => {\n const t = __PRIVATE_checkForAndReportiOSError(e.target.error);\n r(t);\n }, t.onsuccess = t => {\n const r = t.target.result;\n r ? e(r.primaryKey, r.value).next((e => {\n e ? r.continue() : n();\n })) : n();\n };\n }));\n }\n W(e, t) {\n const n = [];\n return new PersistencePromise(((r, i) => {\n e.onerror = e => {\n i(e.target.error);\n }, e.onsuccess = e => {\n const i = e.target.result;\n if (!i) return void r();\n const s = new __PRIVATE_IterationController(i), o = t(i.primaryKey, i.value, s);\n if (o instanceof PersistencePromise) {\n const e = o.catch((e => (s.done(), PersistencePromise.reject(e))));\n n.push(e);\n }\n s.isDone ? r() : null === s.K ? i.continue() : i.continue(s.K);\n };\n })).next((() => PersistencePromise.waitFor(n)));\n }\n options(e, t) {\n let n;\n return void 0 !== e && (\"string\" == typeof e ? n = e : t = e), {\n index: n,\n range: t\n };\n }\n cursor(e) {\n let t = \"next\";\n if (e.reverse && (t = \"prev\"), e.index) {\n const n = this.store.index(e.index);\n return e.H ? n.openKeyCursor(e.range, t) : n.openCursor(e.range, t);\n }\n return this.store.openCursor(e.range, t);\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */ function __PRIVATE_wrapRequest(e) {\n return new PersistencePromise(((t, n) => {\n e.onsuccess = e => {\n const n = e.target.result;\n t(n);\n }, e.onerror = e => {\n const t = __PRIVATE_checkForAndReportiOSError(e.target.error);\n n(t);\n };\n }));\n}\n\n// Guard so we only report the error once.\nlet F = !1;\n\nfunction __PRIVATE_checkForAndReportiOSError(e) {\n const t = __PRIVATE_SimpleDb.S(getUA());\n if (t >= 12.2 && t < 13) {\n const t = \"An internal error was encountered in the Indexed Database server\";\n if (e.message.indexOf(t) >= 0) {\n // Wrap error in a more descriptive one.\n const e = new FirestoreError(\"internal\", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);\n return F || (F = !0, \n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout((() => {\n throw e;\n }), 0)), e;\n }\n }\n return e;\n}\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nclass __PRIVATE_IndexBackfillerScheduler {\n constructor(e, t) {\n this.asyncQueue = e, this.Z = t, this.task = null;\n }\n start() {\n this.X(15e3);\n }\n stop() {\n this.task && (this.task.cancel(), this.task = null);\n }\n get started() {\n return null !== this.task;\n }\n X(e) {\n __PRIVATE_logDebug(\"IndexBackfiller\", `Scheduled in ${e}ms`), this.task = this.asyncQueue.enqueueAfterDelay(\"index_backfill\" /* TimerId.IndexBackfill */ , e, (async () => {\n this.task = null;\n try {\n __PRIVATE_logDebug(\"IndexBackfiller\", `Documents written: ${await this.Z.ee()}`);\n } catch (e) {\n __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(\"IndexBackfiller\", \"Ignoring IndexedDB error during index backfill: \", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n }\n await this.X(6e4);\n }));\n }\n}\n\n/** Implements the steps for backfilling indexes. */ class __PRIVATE_IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n e, t) {\n this.localStore = e, this.persistence = t;\n }\n async ee(e = 50) {\n return this.persistence.runTransaction(\"Backfill Indexes\", \"readwrite-primary\", (t => this.te(t, e)));\n }\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */ te(e, t) {\n const n = new Set;\n let r = t, i = !0;\n return PersistencePromise.doWhile((() => !0 === i && r > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t => {\n if (null !== t && !n.has(t)) return __PRIVATE_logDebug(\"IndexBackfiller\", `Processing collection: ${t}`), \n this.ne(e, t, r).next((e => {\n r -= e, n.add(t);\n }));\n i = !1;\n })))).next((() => t - r));\n }\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */ ne(e, t, n) {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e, t).next((r => this.localStore.localDocuments.getNextDocuments(e, t, r, n).next((n => {\n const i = n.changes;\n return this.localStore.indexManager.updateIndexEntries(e, i).next((() => this.re(r, n))).next((n => (__PRIVATE_logDebug(\"IndexBackfiller\", `Updating offset: ${n}`), \n this.localStore.indexManager.updateCollectionGroup(e, t, n)))).next((() => i.size));\n }))));\n }\n /** Returns the next offset based on the provided documents. */ re(e, t) {\n let n = e;\n return t.changes.forEach(((e, t) => {\n const r = __PRIVATE_newIndexOffsetFromDocument(t);\n __PRIVATE_indexOffsetComparator(r, n) > 0 && (n = r);\n })), new IndexOffset(n.readTime, n.documentKey, Math.max(t.batchId, e.largestBatchId));\n }\n}\n\n/**\n * @license\n * Copyright 2018 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 * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */ class __PRIVATE_ListenSequence {\n constructor(e, t) {\n this.previousValue = e, t && (t.sequenceNumberHandler = e => this.ie(e), this.se = e => t.writeSequenceNumber(e));\n }\n ie(e) {\n return this.previousValue = Math.max(e, this.previousValue), this.previousValue;\n }\n next() {\n const e = ++this.previousValue;\n return this.se && this.se(e), e;\n }\n}\n\n__PRIVATE_ListenSequence.oe = -1;\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction __PRIVATE_isNullOrUndefined(e) {\n return null == e;\n}\n\n/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(e) {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return 0 === e && 1 / e == -1 / 0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */ function isSafeInteger(e) {\n return \"number\" == typeof e && Number.isInteger(e) && !__PRIVATE_isNegativeZero(e) && e <= Number.MAX_SAFE_INTEGER && e >= Number.MIN_SAFE_INTEGER;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction __PRIVATE_encodeResourcePath(e) {\n let t = \"\";\n for (let n = 0; n < e.length; n++) t.length > 0 && (t = __PRIVATE_encodeSeparator(t)), \n t = __PRIVATE_encodeSegment(e.get(n), t);\n return __PRIVATE_encodeSeparator(t);\n}\n\n/** Encodes a single segment of a resource path into the given result */ function __PRIVATE_encodeSegment(e, t) {\n let n = t;\n const r = e.length;\n for (let t = 0; t < r; t++) {\n const r = e.charAt(t);\n switch (r) {\n case \"\\0\":\n n += \"\u0001\u0010\";\n break;\n\n case \"\u0001\":\n n += \"\u0001\u0011\";\n break;\n\n default:\n n += r;\n }\n }\n return n;\n}\n\n/** Encodes a path separator into the given result */ function __PRIVATE_encodeSeparator(e) {\n return e + \"\u0001\u0001\";\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */ function __PRIVATE_decodeResourcePath(e) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const t = e.length;\n if (__PRIVATE_hardAssert(t >= 2), 2 === t) return __PRIVATE_hardAssert(\"\u0001\" === e.charAt(0) && \"\u0001\" === e.charAt(1)), \n ResourcePath.emptyPath();\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const __PRIVATE_lastReasonableEscapeIndex = t - 2, n = [];\n let r = \"\";\n for (let i = 0; i < t; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const t = e.indexOf(\"\u0001\", i);\n (t < 0 || t > __PRIVATE_lastReasonableEscapeIndex) && fail();\n switch (e.charAt(t + 1)) {\n case \"\u0001\":\n const s = e.substring(i, t);\n let o;\n 0 === r.length ? \n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n o = s : (r += s, o = r, r = \"\"), n.push(o);\n break;\n\n case \"\u0010\":\n r += e.substring(i, t), r += \"\\0\";\n break;\n\n case \"\u0011\":\n // The escape character can be used in the output to encode itself.\n r += e.substring(i, t + 1);\n break;\n\n default:\n fail();\n }\n i = t + 2;\n }\n return new ResourcePath(n);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const M = [ \"userId\", \"batchId\" ];\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nfunction __PRIVATE_newDbDocumentMutationPrefixForPath(e, t) {\n return [ e, __PRIVATE_encodeResourcePath(t) ];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */ function __PRIVATE_newDbDocumentMutationKey(e, t, n) {\n return [ e, __PRIVATE_encodeResourcePath(t), n ];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */ const x = {}, O = [ \"prefixPath\", \"collectionGroup\", \"readTime\", \"documentId\" ], N = [ \"prefixPath\", \"collectionGroup\", \"documentId\" ], L = [ \"collectionGroup\", \"readTime\", \"prefixPath\", \"documentId\" ], B = [ \"canonicalId\", \"targetId\" ], k = [ \"targetId\", \"path\" ], q = [ \"path\", \"targetId\" ], Q = [ \"collectionId\", \"parent\" ], K = [ \"indexId\", \"uid\" ], $ = [ \"uid\", \"sequenceNumber\" ], U = [ \"indexId\", \"uid\", \"arrayValue\", \"directionalValue\", \"orderedDocumentKey\", \"documentKey\" ], W = [ \"indexId\", \"uid\", \"orderedDocumentKey\" ], G = [ \"userId\", \"collectionPath\", \"documentId\" ], z = [ \"userId\", \"collectionPath\", \"largestBatchId\" ], j = [ \"userId\", \"collectionGroup\", \"largestBatchId\" ], H = [ ...[ ...[ ...[ ...[ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocuments\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\" ], \"clientMetadata\" ], \"remoteDocumentGlobal\" ], \"collectionParents\" ], \"bundles\", \"namedQueries\" ], J = [ ...H, \"documentOverlays\" ], Y = [ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocumentsV14\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\", \"clientMetadata\", \"remoteDocumentGlobal\", \"collectionParents\", \"bundles\", \"namedQueries\", \"documentOverlays\" ], Z = Y, X = [ ...Z, \"indexConfiguration\", \"indexState\", \"indexEntries\" ], ee = X, te = [ ...X, \"globals\" ];\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 */\nclass __PRIVATE_IndexedDbTransaction extends PersistenceTransaction {\n constructor(e, t) {\n super(), this._e = e, this.currentSequenceNumber = t;\n }\n}\n\nfunction __PRIVATE_getStore(e, t) {\n const n = __PRIVATE_debugCast(e);\n return __PRIVATE_SimpleDb.F(n._e, t);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_objectSize(e) {\n let t = 0;\n for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t++;\n return t;\n}\n\nfunction forEach(e, t) {\n for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t(n, e[n]);\n}\n\nfunction __PRIVATE_mapToArray(e, t) {\n const n = [];\n for (const r in e) Object.prototype.hasOwnProperty.call(e, r) && n.push(t(e[r], r, e));\n return n;\n}\n\nfunction isEmpty(e) {\n for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return !1;\n return !0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nclass SortedMap {\n constructor(e, t) {\n this.comparator = e, this.root = t || LLRBNode.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(e, t) {\n return new SortedMap(this.comparator, this.root.insert(e, t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));\n }\n // Returns a copy of the map, with the specified key removed.\n remove(e) {\n return new SortedMap(this.comparator, this.root.remove(e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));\n }\n // Returns the value of the node with the given key, or null.\n get(e) {\n let t = this.root;\n for (;!t.isEmpty(); ) {\n const n = this.comparator(e, t.key);\n if (0 === n) return t.value;\n n < 0 ? t = t.left : n > 0 && (t = t.right);\n }\n return null;\n }\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(e) {\n // Number of nodes that were pruned when descending right\n let t = 0, n = this.root;\n for (;!n.isEmpty(); ) {\n const r = this.comparator(e, n.key);\n if (0 === r) return t + n.left.size;\n r < 0 ? n = n.left : (\n // Count all nodes left of the node plus the node itself\n t += n.left.size + 1, n = n.right);\n }\n // Node not found\n return -1;\n }\n isEmpty() {\n return this.root.isEmpty();\n }\n // Returns the total number of nodes in the map.\n get size() {\n return this.root.size;\n }\n // Returns the minimum key in the map.\n minKey() {\n return this.root.minKey();\n }\n // Returns the maximum key in the map.\n maxKey() {\n return this.root.maxKey();\n }\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(e) {\n return this.root.inorderTraversal(e);\n }\n forEach(e) {\n this.inorderTraversal(((t, n) => (e(t, n), !1)));\n }\n toString() {\n const e = [];\n return this.inorderTraversal(((t, n) => (e.push(`${t}:${n}`), !1))), `{${e.join(\", \")}}`;\n }\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(e) {\n return this.root.reverseTraversal(e);\n }\n // Returns an iterator over the SortedMap.\n getIterator() {\n return new SortedMapIterator(this.root, null, this.comparator, !1);\n }\n getIteratorFrom(e) {\n return new SortedMapIterator(this.root, e, this.comparator, !1);\n }\n getReverseIterator() {\n return new SortedMapIterator(this.root, null, this.comparator, !0);\n }\n getReverseIteratorFrom(e) {\n return new SortedMapIterator(this.root, e, this.comparator, !0);\n }\n}\n\n // end SortedMap\n// An iterator over an LLRBNode.\nclass SortedMapIterator {\n constructor(e, t, n, r) {\n this.isReverse = r, this.nodeStack = [];\n let i = 1;\n for (;!e.isEmpty(); ) if (i = t ? n(e.key, t) : 1, \n // flip the comparison if we're going in reverse\n t && r && (i *= -1), i < 0) \n // This node is less than our start key. ignore it\n e = this.isReverse ? e.left : e.right; else {\n if (0 === i) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(e);\n break;\n }\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(e), e = this.isReverse ? e.right : e.left;\n }\n }\n getNext() {\n let e = this.nodeStack.pop();\n const t = {\n key: e.key,\n value: e.value\n };\n if (this.isReverse) for (e = e.left; !e.isEmpty(); ) this.nodeStack.push(e), e = e.right; else for (e = e.right; !e.isEmpty(); ) this.nodeStack.push(e), \n e = e.left;\n return t;\n }\n hasNext() {\n return this.nodeStack.length > 0;\n }\n peek() {\n if (0 === this.nodeStack.length) return null;\n const e = this.nodeStack[this.nodeStack.length - 1];\n return {\n key: e.key,\n value: e.value\n };\n }\n}\n\n // end SortedMapIterator\n// Represents a node in a Left-leaning Red-Black tree.\nclass LLRBNode {\n constructor(e, t, n, r, i) {\n this.key = e, this.value = t, this.color = null != n ? n : LLRBNode.RED, this.left = null != r ? r : LLRBNode.EMPTY, \n this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(e, t, n, r, i) {\n return new LLRBNode(null != e ? e : this.key, null != t ? t : this.value, null != n ? n : this.color, null != r ? r : this.left, null != i ? i : this.right);\n }\n isEmpty() {\n return !1;\n }\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(e) {\n return this.left.inorderTraversal(e) || e(this.key, this.value) || this.right.inorderTraversal(e);\n }\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(e) {\n return this.right.reverseTraversal(e) || e(this.key, this.value) || this.left.reverseTraversal(e);\n }\n // Returns the minimum node in the tree.\n min() {\n return this.left.isEmpty() ? this : this.left.min();\n }\n // Returns the maximum key in the tree.\n minKey() {\n return this.min().key;\n }\n // Returns the maximum key in the tree.\n maxKey() {\n return this.right.isEmpty() ? this.key : this.right.maxKey();\n }\n // Returns new tree, with the key/value added.\n insert(e, t, n) {\n let r = this;\n const i = n(e, r.key);\n return r = i < 0 ? r.copy(null, null, null, r.left.insert(e, t, n), null) : 0 === i ? r.copy(null, t, null, null, null) : r.copy(null, null, null, null, r.right.insert(e, t, n)), \n r.fixUp();\n }\n removeMin() {\n if (this.left.isEmpty()) return LLRBNode.EMPTY;\n let e = this;\n return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), e = e.copy(null, null, null, e.left.removeMin(), null), \n e.fixUp();\n }\n // Returns new tree, with the specified item removed.\n remove(e, t) {\n let n, r = this;\n if (t(e, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()), \n r = r.copy(null, null, null, r.left.remove(e, t), null); else {\n if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()), \n 0 === t(e, r.key)) {\n if (r.right.isEmpty()) return LLRBNode.EMPTY;\n n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin());\n }\n r = r.copy(null, null, null, null, r.right.remove(e, t));\n }\n return r.fixUp();\n }\n isRed() {\n return this.color;\n }\n // Returns new tree after performing any needed rotations.\n fixUp() {\n let e = this;\n return e.right.isRed() && !e.left.isRed() && (e = e.rotateLeft()), e.left.isRed() && e.left.left.isRed() && (e = e.rotateRight()), \n e.left.isRed() && e.right.isRed() && (e = e.colorFlip()), e;\n }\n moveRedLeft() {\n let e = this.colorFlip();\n return e.right.left.isRed() && (e = e.copy(null, null, null, null, e.right.rotateRight()), \n e = e.rotateLeft(), e = e.colorFlip()), e;\n }\n moveRedRight() {\n let e = this.colorFlip();\n return e.left.left.isRed() && (e = e.rotateRight(), e = e.colorFlip()), e;\n }\n rotateLeft() {\n const e = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, e, null);\n }\n rotateRight() {\n const e = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, e);\n }\n colorFlip() {\n const e = this.left.copy(null, null, !this.left.color, null, null), t = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, e, t);\n }\n // For testing.\n checkMaxDepth() {\n const e = this.check();\n return Math.pow(2, e) <= this.size + 1;\n }\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n check() {\n if (this.isRed() && this.left.isRed()) throw fail();\n if (this.right.isRed()) throw fail();\n const e = this.left.check();\n if (e !== this.right.check()) throw fail();\n return e + (this.isRed() ? 0 : 1);\n }\n}\n\n // end LLRBNode\n// Empty node is shared between all LLRB trees.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nLLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1;\n\n// end LLRBEmptyNode\nLLRBNode.EMPTY = new \n// Represents an empty node (a leaf node in the Red-Black Tree).\nclass LLRBEmptyNode {\n constructor() {\n this.size = 0;\n }\n get key() {\n throw fail();\n }\n get value() {\n throw fail();\n }\n get color() {\n throw fail();\n }\n get left() {\n throw fail();\n }\n get right() {\n throw fail();\n }\n // Returns a copy of the current node.\n copy(e, t, n, r, i) {\n return this;\n }\n // Returns a copy of the tree, with the specified key/value added.\n insert(e, t, n) {\n return new LLRBNode(e, t);\n }\n // Returns a copy of the tree, with the specified key removed.\n remove(e, t) {\n return this;\n }\n isEmpty() {\n return !0;\n }\n inorderTraversal(e) {\n return !1;\n }\n reverseTraversal(e) {\n return !1;\n }\n minKey() {\n return null;\n }\n maxKey() {\n return null;\n }\n isRed() {\n return !1;\n }\n // For testing.\n checkMaxDepth() {\n return !0;\n }\n check() {\n return 0;\n }\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nclass SortedSet {\n constructor(e) {\n this.comparator = e, this.data = new SortedMap(this.comparator);\n }\n has(e) {\n return null !== this.data.get(e);\n }\n first() {\n return this.data.minKey();\n }\n last() {\n return this.data.maxKey();\n }\n get size() {\n return this.data.size;\n }\n indexOf(e) {\n return this.data.indexOf(e);\n }\n /** Iterates elements in order defined by \"comparator\" */ forEach(e) {\n this.data.inorderTraversal(((t, n) => (e(t), !1)));\n }\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(e, t) {\n const n = this.data.getIteratorFrom(e[0]);\n for (;n.hasNext(); ) {\n const r = n.getNext();\n if (this.comparator(r.key, e[1]) >= 0) return;\n t(r.key);\n }\n }\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */ forEachWhile(e, t) {\n let n;\n for (n = void 0 !== t ? this.data.getIteratorFrom(t) : this.data.getIterator(); n.hasNext(); ) {\n if (!e(n.getNext().key)) return;\n }\n }\n /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(e) {\n const t = this.data.getIteratorFrom(e);\n return t.hasNext() ? t.getNext().key : null;\n }\n getIterator() {\n return new SortedSetIterator(this.data.getIterator());\n }\n getIteratorFrom(e) {\n return new SortedSetIterator(this.data.getIteratorFrom(e));\n }\n /** Inserts or updates an element */ add(e) {\n return this.copy(this.data.remove(e).insert(e, !0));\n }\n /** Deletes an element */ delete(e) {\n return this.has(e) ? this.copy(this.data.remove(e)) : this;\n }\n isEmpty() {\n return this.data.isEmpty();\n }\n unionWith(e) {\n let t = this;\n // Make sure `result` always refers to the larger one of the two sets.\n return t.size < e.size && (t = e, e = this), e.forEach((e => {\n t = t.add(e);\n })), t;\n }\n isEqual(e) {\n if (!(e instanceof SortedSet)) return !1;\n if (this.size !== e.size) return !1;\n const t = this.data.getIterator(), n = e.data.getIterator();\n for (;t.hasNext(); ) {\n const e = t.getNext().key, r = n.getNext().key;\n if (0 !== this.comparator(e, r)) return !1;\n }\n return !0;\n }\n toArray() {\n const e = [];\n return this.forEach((t => {\n e.push(t);\n })), e;\n }\n toString() {\n const e = [];\n return this.forEach((t => e.push(t))), \"SortedSet(\" + e.toString() + \")\";\n }\n copy(e) {\n const t = new SortedSet(this.comparator);\n return t.data = e, t;\n }\n}\n\nclass SortedSetIterator {\n constructor(e) {\n this.iter = e;\n }\n getNext() {\n return this.iter.getNext().key;\n }\n hasNext() {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction __PRIVATE_advanceIterator(e) {\n return e.hasNext() ? e.getNext() : void 0;\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 * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */ class FieldMask {\n constructor(e) {\n this.fields = e, \n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n e.sort(FieldPath$1.comparator);\n }\n static empty() {\n return new FieldMask([]);\n }\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */ unionWith(e) {\n let t = new SortedSet(FieldPath$1.comparator);\n for (const e of this.fields) t = t.add(e);\n for (const n of e) t = t.add(n);\n return new FieldMask(t.toArray());\n }\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */ covers(e) {\n for (const t of this.fields) if (t.isPrefixOf(e)) return !0;\n return !1;\n }\n isEqual(e) {\n return __PRIVATE_arrayEquals(this.fields, e.fields, ((e, t) => e.isEqual(t)));\n }\n}\n\n/**\n * @license\n * Copyright 2023 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 * An error encountered while decoding base64 string.\n */ class __PRIVATE_Base64DecodeError extends Error {\n constructor() {\n super(...arguments), this.name = \"Base64DecodeError\";\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/** Converts a Base64 encoded string to a binary string. */\n/** True if and only if the Base64 conversion functions are available. */\nfunction __PRIVATE_isBase64Available() {\n return \"undefined\" != typeof atob;\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 * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */ class ByteString {\n constructor(e) {\n this.binaryString = e;\n }\n static fromBase64String(e) {\n const t = function __PRIVATE_decodeBase64(e) {\n try {\n return atob(e);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n throw \"undefined\" != typeof DOMException && e instanceof DOMException ? new __PRIVATE_Base64DecodeError(\"Invalid base64 string: \" + e) : e;\n }\n }\n /** Converts a binary string to a Base64 encoded string. */ (e);\n return new ByteString(t);\n }\n static fromUint8Array(e) {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const t = \n /**\n * Helper function to convert an Uint8array to a binary string.\n */\n function __PRIVATE_binaryStringFromUint8Array(e) {\n let t = \"\";\n for (let n = 0; n < e.length; ++n) t += String.fromCharCode(e[n]);\n return t;\n }\n /**\n * Helper function to convert a binary string to an Uint8Array.\n */ (e);\n return new ByteString(t);\n }\n [Symbol.iterator]() {\n let e = 0;\n return {\n next: () => e < this.binaryString.length ? {\n value: this.binaryString.charCodeAt(e++),\n done: !1\n } : {\n value: void 0,\n done: !0\n }\n };\n }\n toBase64() {\n return function __PRIVATE_encodeBase64(e) {\n return btoa(e);\n }(this.binaryString);\n }\n toUint8Array() {\n return function __PRIVATE_uint8ArrayFromBinaryString(e) {\n const t = new Uint8Array(e.length);\n for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n);\n return t;\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 // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\n (this.binaryString);\n }\n approximateByteSize() {\n return 2 * this.binaryString.length;\n }\n compareTo(e) {\n return __PRIVATE_primitiveComparator(this.binaryString, e.binaryString);\n }\n isEqual(e) {\n return this.binaryString === e.binaryString;\n }\n}\n\nByteString.EMPTY_BYTE_STRING = new ByteString(\"\");\n\nconst ne = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */ function __PRIVATE_normalizeTimestamp(e) {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (__PRIVATE_hardAssert(!!e), \"string\" == typeof e) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n let t = 0;\n const n = ne.exec(e);\n if (__PRIVATE_hardAssert(!!n), n[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let e = n[1];\n e = (e + \"000000000\").substr(0, 9), t = Number(e);\n }\n // Parse the date to get the seconds.\n const r = new Date(e);\n return {\n seconds: Math.floor(r.getTime() / 1e3),\n nanos: t\n };\n }\n return {\n seconds: __PRIVATE_normalizeNumber(e.seconds),\n nanos: __PRIVATE_normalizeNumber(e.nanos)\n };\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */ function __PRIVATE_normalizeNumber(e) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n return \"number\" == typeof e ? e : \"string\" == typeof e ? Number(e) : 0;\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(e) {\n return \"string\" == typeof e ? ByteString.fromBase64String(e) : ByteString.fromUint8Array(e);\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 * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */ function __PRIVATE_isServerTimestamp(e) {\n var t, n;\n return \"server_timestamp\" === (null === (n = ((null === (t = null == e ? void 0 : e.mapValue) || void 0 === t ? void 0 : t.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nfunction __PRIVATE_getPreviousValue(e) {\n const t = e.mapValue.fields.__previous_value__;\n return __PRIVATE_isServerTimestamp(t) ? __PRIVATE_getPreviousValue(t) : t;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */ function __PRIVATE_getLocalWriteTime(e) {\n const t = __PRIVATE_normalizeTimestamp(e.mapValue.fields.__local_write_time__.timestampValue);\n return new Timestamp(t.seconds, t.nanos);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(e, t, n, r, i, s, o, _, a) {\n this.databaseId = e, this.appId = t, this.persistenceKey = n, this.host = r, this.ssl = i, \n this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = _, \n this.useFetchStreams = a;\n }\n}\n\n/** The default database name for a project. */\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nclass DatabaseId {\n constructor(e, t) {\n this.projectId = e, this.database = t || \"(default)\";\n }\n static empty() {\n return new DatabaseId(\"\", \"\");\n }\n get isDefaultDatabase() {\n return \"(default)\" === this.database;\n }\n isEqual(e) {\n return e instanceof DatabaseId && e.projectId === this.projectId && e.database === this.database;\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 */\nconst re = {\n mapValue: {\n fields: {\n __type__: {\n stringValue: \"__max__\"\n }\n }\n }\n}, ie = {\n nullValue: \"NULL_VALUE\"\n};\n\n/** Extracts the backend's type order for the provided value. */\nfunction __PRIVATE_typeOrder(e) {\n return \"nullValue\" in e ? 0 /* TypeOrder.NullValue */ : \"booleanValue\" in e ? 1 /* TypeOrder.BooleanValue */ : \"integerValue\" in e || \"doubleValue\" in e ? 2 /* TypeOrder.NumberValue */ : \"timestampValue\" in e ? 3 /* TypeOrder.TimestampValue */ : \"stringValue\" in e ? 5 /* TypeOrder.StringValue */ : \"bytesValue\" in e ? 6 /* TypeOrder.BlobValue */ : \"referenceValue\" in e ? 7 /* TypeOrder.RefValue */ : \"geoPointValue\" in e ? 8 /* TypeOrder.GeoPointValue */ : \"arrayValue\" in e ? 9 /* TypeOrder.ArrayValue */ : \"mapValue\" in e ? __PRIVATE_isServerTimestamp(e) ? 4 /* TypeOrder.ServerTimestampValue */ : __PRIVATE_isMaxValue(e) ? 9007199254740991 /* TypeOrder.MaxValue */ : __PRIVATE_isVectorValue(e) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail();\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(e, t) {\n if (e === t) return !0;\n const n = __PRIVATE_typeOrder(e);\n if (n !== __PRIVATE_typeOrder(t)) return !1;\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return !0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return e.booleanValue === t.booleanValue;\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t));\n\n case 3 /* TypeOrder.TimestampValue */ :\n return function __PRIVATE_timestampEquals(e, t) {\n if (\"string\" == typeof e.timestampValue && \"string\" == typeof t.timestampValue && e.timestampValue.length === t.timestampValue.length) \n // Use string equality for ISO 8601 timestamps\n return e.timestampValue === t.timestampValue;\n const n = __PRIVATE_normalizeTimestamp(e.timestampValue), r = __PRIVATE_normalizeTimestamp(t.timestampValue);\n return n.seconds === r.seconds && n.nanos === r.nanos;\n }(e, t);\n\n case 5 /* TypeOrder.StringValue */ :\n return e.stringValue === t.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return function __PRIVATE_blobEquals(e, t) {\n return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(t.bytesValue));\n }(e, t);\n\n case 7 /* TypeOrder.RefValue */ :\n return e.referenceValue === t.referenceValue;\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function __PRIVATE_geoPointEquals(e, t) {\n return __PRIVATE_normalizeNumber(e.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t.geoPointValue.longitude);\n }(e, t);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function __PRIVATE_numberEquals(e, t) {\n if (\"integerValue\" in e && \"integerValue\" in t) return __PRIVATE_normalizeNumber(e.integerValue) === __PRIVATE_normalizeNumber(t.integerValue);\n if (\"doubleValue\" in e && \"doubleValue\" in t) {\n const n = __PRIVATE_normalizeNumber(e.doubleValue), r = __PRIVATE_normalizeNumber(t.doubleValue);\n return n === r ? __PRIVATE_isNegativeZero(n) === __PRIVATE_isNegativeZero(r) : isNaN(n) && isNaN(r);\n }\n return !1;\n }(e, t);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return __PRIVATE_arrayEquals(e.arrayValue.values || [], t.arrayValue.values || [], __PRIVATE_valueEquals);\n\n case 10 /* TypeOrder.VectorValue */ :\n case 11 /* TypeOrder.ObjectValue */ :\n return function __PRIVATE_objectEquals(e, t) {\n const n = e.mapValue.fields || {}, r = t.mapValue.fields || {};\n if (__PRIVATE_objectSize(n) !== __PRIVATE_objectSize(r)) return !1;\n for (const e in n) if (n.hasOwnProperty(e) && (void 0 === r[e] || !__PRIVATE_valueEquals(n[e], r[e]))) return !1;\n return !0;\n }\n /** Returns true if the ArrayValue contains the specified element. */ (e, t);\n\n default:\n return fail();\n }\n}\n\nfunction __PRIVATE_arrayValueContains(e, t) {\n return void 0 !== (e.values || []).find((e => __PRIVATE_valueEquals(e, t)));\n}\n\nfunction __PRIVATE_valueCompare(e, t) {\n if (e === t) return 0;\n const n = __PRIVATE_typeOrder(e), r = __PRIVATE_typeOrder(t);\n if (n !== r) return __PRIVATE_primitiveComparator(n, r);\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return 0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return __PRIVATE_primitiveComparator(e.booleanValue, t.booleanValue);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function __PRIVATE_compareNumbers(e, t) {\n const n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue), r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue);\n return n < r ? -1 : n > r ? 1 : n === r ? 0 : \n // one or both are NaN.\n isNaN(n) ? isNaN(r) ? 0 : -1 : 1;\n }(e, t);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return __PRIVATE_compareTimestamps(e.timestampValue, t.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e), __PRIVATE_getLocalWriteTime(t));\n\n case 5 /* TypeOrder.StringValue */ :\n return __PRIVATE_primitiveComparator(e.stringValue, t.stringValue);\n\n case 6 /* TypeOrder.BlobValue */ :\n return function __PRIVATE_compareBlobs(e, t) {\n const n = __PRIVATE_normalizeByteString(e), r = __PRIVATE_normalizeByteString(t);\n return n.compareTo(r);\n }(e.bytesValue, t.bytesValue);\n\n case 7 /* TypeOrder.RefValue */ :\n return function __PRIVATE_compareReferences(e, t) {\n const n = e.split(\"/\"), r = t.split(\"/\");\n for (let e = 0; e < n.length && e < r.length; e++) {\n const t = __PRIVATE_primitiveComparator(n[e], r[e]);\n if (0 !== t) return t;\n }\n return __PRIVATE_primitiveComparator(n.length, r.length);\n }(e.referenceValue, t.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function __PRIVATE_compareGeoPoints(e, t) {\n const n = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(t.latitude));\n if (0 !== n) return n;\n return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude), __PRIVATE_normalizeNumber(t.longitude));\n }(e.geoPointValue, t.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return __PRIVATE_compareArrays(e.arrayValue, t.arrayValue);\n\n case 10 /* TypeOrder.VectorValue */ :\n return function __PRIVATE_compareVectors(e, t) {\n var n, r, i, s;\n const o = e.fields || {}, _ = t.fields || {}, a = null === (n = o.value) || void 0 === n ? void 0 : n.arrayValue, u = null === (r = _.value) || void 0 === r ? void 0 : r.arrayValue, c = __PRIVATE_primitiveComparator((null === (i = null == a ? void 0 : a.values) || void 0 === i ? void 0 : i.length) || 0, (null === (s = null == u ? void 0 : u.values) || void 0 === s ? void 0 : s.length) || 0);\n if (0 !== c) return c;\n return __PRIVATE_compareArrays(a, u);\n }(e.mapValue, t.mapValue);\n\n case 11 /* TypeOrder.ObjectValue */ :\n return function __PRIVATE_compareMaps(e, t) {\n if (e === re.mapValue && t === re.mapValue) return 0;\n if (e === re.mapValue) return 1;\n if (t === re.mapValue) return -1;\n const n = e.fields || {}, r = Object.keys(n), i = t.fields || {}, s = Object.keys(i);\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n r.sort(), s.sort();\n for (let e = 0; e < r.length && e < s.length; ++e) {\n const t = __PRIVATE_primitiveComparator(r[e], s[e]);\n if (0 !== t) return t;\n const o = __PRIVATE_valueCompare(n[r[e]], i[s[e]]);\n if (0 !== o) return o;\n }\n return __PRIVATE_primitiveComparator(r.length, s.length);\n }\n /**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */ (e.mapValue, t.mapValue);\n\n default:\n throw fail();\n }\n}\n\nfunction __PRIVATE_compareTimestamps(e, t) {\n if (\"string\" == typeof e && \"string\" == typeof t && e.length === t.length) return __PRIVATE_primitiveComparator(e, t);\n const n = __PRIVATE_normalizeTimestamp(e), r = __PRIVATE_normalizeTimestamp(t), i = __PRIVATE_primitiveComparator(n.seconds, r.seconds);\n return 0 !== i ? i : __PRIVATE_primitiveComparator(n.nanos, r.nanos);\n}\n\nfunction __PRIVATE_compareArrays(e, t) {\n const n = e.values || [], r = t.values || [];\n for (let e = 0; e < n.length && e < r.length; ++e) {\n const t = __PRIVATE_valueCompare(n[e], r[e]);\n if (t) return t;\n }\n return __PRIVATE_primitiveComparator(n.length, r.length);\n}\n\nfunction canonicalId(e) {\n return __PRIVATE_canonifyValue(e);\n}\n\nfunction __PRIVATE_canonifyValue(e) {\n return \"nullValue\" in e ? \"null\" : \"booleanValue\" in e ? \"\" + e.booleanValue : \"integerValue\" in e ? \"\" + e.integerValue : \"doubleValue\" in e ? \"\" + e.doubleValue : \"timestampValue\" in e ? function __PRIVATE_canonifyTimestamp(e) {\n const t = __PRIVATE_normalizeTimestamp(e);\n return `time(${t.seconds},${t.nanos})`;\n }(e.timestampValue) : \"stringValue\" in e ? e.stringValue : \"bytesValue\" in e ? function __PRIVATE_canonifyByteString(e) {\n return __PRIVATE_normalizeByteString(e).toBase64();\n }(e.bytesValue) : \"referenceValue\" in e ? function __PRIVATE_canonifyReference(e) {\n return DocumentKey.fromName(e).toString();\n }(e.referenceValue) : \"geoPointValue\" in e ? function __PRIVATE_canonifyGeoPoint(e) {\n return `geo(${e.latitude},${e.longitude})`;\n }(e.geoPointValue) : \"arrayValue\" in e ? function __PRIVATE_canonifyArray(e) {\n let t = \"[\", n = !0;\n for (const r of e.values || []) n ? n = !1 : t += \",\", t += __PRIVATE_canonifyValue(r);\n return t + \"]\";\n }\n /**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */ (e.arrayValue) : \"mapValue\" in e ? function __PRIVATE_canonifyMap(e) {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const t = Object.keys(e.fields || {}).sort();\n let n = \"{\", r = !0;\n for (const i of t) r ? r = !1 : n += \",\", n += `${i}:${__PRIVATE_canonifyValue(e.fields[i])}`;\n return n + \"}\";\n }(e.mapValue) : fail();\n}\n\nfunction __PRIVATE_estimateByteSize(e) {\n switch (__PRIVATE_typeOrder(e)) {\n case 0 /* TypeOrder.NullValue */ :\n case 1 /* TypeOrder.BooleanValue */ :\n return 4;\n\n case 2 /* TypeOrder.NumberValue */ :\n return 8;\n\n case 3 /* TypeOrder.TimestampValue */ :\n case 8 /* TypeOrder.GeoPointValue */ :\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n const t = __PRIVATE_getPreviousValue(e);\n return t ? 16 + __PRIVATE_estimateByteSize(t) : 16;\n\n case 5 /* TypeOrder.StringValue */ :\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return 2 * e.stringValue.length;\n\n case 6 /* TypeOrder.BlobValue */ :\n return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize();\n\n case 7 /* TypeOrder.RefValue */ :\n return e.referenceValue.length;\n\n case 9 /* TypeOrder.ArrayValue */ :\n return function __PRIVATE_estimateArrayByteSize(e) {\n return (e.values || []).reduce(((e, t) => e + __PRIVATE_estimateByteSize(t)), 0);\n }\n /** Returns a reference value for the provided database and key. */ (e.arrayValue);\n\n case 10 /* TypeOrder.VectorValue */ :\n case 11 /* TypeOrder.ObjectValue */ :\n return function __PRIVATE_estimateMapByteSize(e) {\n let t = 0;\n return forEach(e.fields, ((e, n) => {\n t += e.length + __PRIVATE_estimateByteSize(n);\n })), t;\n }(e.mapValue);\n\n default:\n throw fail();\n }\n}\n\nfunction __PRIVATE_refValue(e, t) {\n return {\n referenceValue: `projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */ function isInteger(e) {\n return !!e && \"integerValue\" in e;\n}\n\n/** Returns true if `value` is a DoubleValue. */\n/** Returns true if `value` is an ArrayValue. */\nfunction isArray(e) {\n return !!e && \"arrayValue\" in e;\n}\n\n/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(e) {\n return !!e && \"nullValue\" in e;\n}\n\n/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(e) {\n return !!e && \"doubleValue\" in e && isNaN(Number(e.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(e) {\n return !!e && \"mapValue\" in e;\n}\n\n/** Returns true if `value` is a VetorValue. */ function __PRIVATE_isVectorValue(e) {\n var t, n;\n return \"__vector__\" === (null === (n = ((null === (t = null == e ? void 0 : e.mapValue) || void 0 === t ? void 0 : t.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);\n}\n\n/** Creates a deep copy of `source`. */ function __PRIVATE_deepClone(e) {\n if (e.geoPointValue) return {\n geoPointValue: Object.assign({}, e.geoPointValue)\n };\n if (e.timestampValue && \"object\" == typeof e.timestampValue) return {\n timestampValue: Object.assign({}, e.timestampValue)\n };\n if (e.mapValue) {\n const t = {\n mapValue: {\n fields: {}\n }\n };\n return forEach(e.mapValue.fields, ((e, n) => t.mapValue.fields[e] = __PRIVATE_deepClone(n))), \n t;\n }\n if (e.arrayValue) {\n const t = {\n arrayValue: {\n values: []\n }\n };\n for (let n = 0; n < (e.arrayValue.values || []).length; ++n) t.arrayValue.values[n] = __PRIVATE_deepClone(e.arrayValue.values[n]);\n return t;\n }\n return Object.assign({}, e);\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function __PRIVATE_isMaxValue(e) {\n return \"__max__\" === (((e.mapValue || {}).fields || {}).__type__ || {}).stringValue;\n}\n\nconst se = {\n mapValue: {\n fields: {\n __type__: {\n stringValue: \"__vector__\"\n },\n value: {\n arrayValue: {}\n }\n }\n }\n};\n\n/** Returns the lowest value for the given value type (inclusive). */ function __PRIVATE_valuesGetLowerBound(e) {\n return \"nullValue\" in e ? ie : \"booleanValue\" in e ? {\n booleanValue: !1\n } : \"integerValue\" in e || \"doubleValue\" in e ? {\n doubleValue: NaN\n } : \"timestampValue\" in e ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"stringValue\" in e ? {\n stringValue: \"\"\n } : \"bytesValue\" in e ? {\n bytesValue: \"\"\n } : \"referenceValue\" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : \"geoPointValue\" in e ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"arrayValue\" in e ? {\n arrayValue: {}\n } : \"mapValue\" in e ? __PRIVATE_isVectorValue(e) ? se : {\n mapValue: {}\n } : fail();\n}\n\n/** Returns the largest value for the given value type (exclusive). */ function __PRIVATE_valuesGetUpperBound(e) {\n return \"nullValue\" in e ? {\n booleanValue: !1\n } : \"booleanValue\" in e ? {\n doubleValue: NaN\n } : \"integerValue\" in e || \"doubleValue\" in e ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"timestampValue\" in e ? {\n stringValue: \"\"\n } : \"stringValue\" in e ? {\n bytesValue: \"\"\n } : \"bytesValue\" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : \"referenceValue\" in e ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"geoPointValue\" in e ? {\n arrayValue: {}\n } : \"arrayValue\" in e ? se : \"mapValue\" in e ? __PRIVATE_isVectorValue(e) ? {\n mapValue: {}\n } : re : fail();\n}\n\nfunction __PRIVATE_lowerBoundCompare(e, t) {\n const n = __PRIVATE_valueCompare(e.value, t.value);\n return 0 !== n ? n : e.inclusive && !t.inclusive ? -1 : !e.inclusive && t.inclusive ? 1 : 0;\n}\n\nfunction __PRIVATE_upperBoundCompare(e, t) {\n const n = __PRIVATE_valueCompare(e.value, t.value);\n return 0 !== n ? n : e.inclusive && !t.inclusive ? 1 : !e.inclusive && t.inclusive ? -1 : 0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */ class ObjectValue {\n constructor(e) {\n this.value = e;\n }\n static empty() {\n return new ObjectValue({\n mapValue: {}\n });\n }\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */ field(e) {\n if (e.isEmpty()) return this.value;\n {\n let t = this.value;\n for (let n = 0; n < e.length - 1; ++n) if (t = (t.mapValue.fields || {})[e.get(n)], \n !__PRIVATE_isMapValue(t)) return null;\n return t = (t.mapValue.fields || {})[e.lastSegment()], t || null;\n }\n }\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */ set(e, t) {\n this.getFieldsMap(e.popLast())[e.lastSegment()] = __PRIVATE_deepClone(t);\n }\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */ setAll(e) {\n let t = FieldPath$1.emptyPath(), n = {}, r = [];\n e.forEach(((e, i) => {\n if (!t.isImmediateParentOf(i)) {\n // Insert the accumulated changes at this parent location\n const e = this.getFieldsMap(t);\n this.applyChanges(e, n, r), n = {}, r = [], t = i.popLast();\n }\n e ? n[i.lastSegment()] = __PRIVATE_deepClone(e) : r.push(i.lastSegment());\n }));\n const i = this.getFieldsMap(t);\n this.applyChanges(i, n, r);\n }\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */ delete(e) {\n const t = this.field(e.popLast());\n __PRIVATE_isMapValue(t) && t.mapValue.fields && delete t.mapValue.fields[e.lastSegment()];\n }\n isEqual(e) {\n return __PRIVATE_valueEquals(this.value, e.value);\n }\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */ getFieldsMap(e) {\n let t = this.value;\n t.mapValue.fields || (t.mapValue = {\n fields: {}\n });\n for (let n = 0; n < e.length; ++n) {\n let r = t.mapValue.fields[e.get(n)];\n __PRIVATE_isMapValue(r) && r.mapValue.fields || (r = {\n mapValue: {\n fields: {}\n }\n }, t.mapValue.fields[e.get(n)] = r), t = r;\n }\n return t.mapValue.fields;\n }\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */ applyChanges(e, t, n) {\n forEach(t, ((t, n) => e[t] = n));\n for (const t of n) delete e[t];\n }\n clone() {\n return new ObjectValue(__PRIVATE_deepClone(this.value));\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */ function __PRIVATE_extractFieldMask(e) {\n const t = [];\n return forEach(e.fields, ((e, n) => {\n const r = new FieldPath$1([ e ]);\n if (__PRIVATE_isMapValue(n)) {\n const e = __PRIVATE_extractFieldMask(n.mapValue).fields;\n if (0 === e.length) \n // Preserve the empty map by adding it to the FieldMask.\n t.push(r); else \n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const n of e) t.push(r.child(n));\n } else \n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n t.push(r);\n })), new FieldMask(t);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */ class MutableDocument {\n constructor(e, t, n, r, i, s, o) {\n this.key = e, this.documentType = t, this.version = n, this.readTime = r, this.createTime = i, \n this.data = s, this.documentState = o;\n }\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */ static newInvalidDocument(e) {\n return new MutableDocument(e, 0 /* DocumentType.INVALID */ , \n /* version */ SnapshotVersion.min(), \n /* readTime */ SnapshotVersion.min(), \n /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */ static newFoundDocument(e, t, n, r) {\n return new MutableDocument(e, 1 /* DocumentType.FOUND_DOCUMENT */ , \n /* version */ t, \n /* readTime */ SnapshotVersion.min(), \n /* createTime */ n, r, 0 /* DocumentState.SYNCED */);\n }\n /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(e, t) {\n return new MutableDocument(e, 2 /* DocumentType.NO_DOCUMENT */ , \n /* version */ t, \n /* readTime */ SnapshotVersion.min(), \n /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */ static newUnknownDocument(e, t) {\n return new MutableDocument(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n /* version */ t, \n /* readTime */ SnapshotVersion.min(), \n /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);\n }\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */ convertToFoundDocument(e, t) {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = e), \n this.version = e, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = t, \n this.documentState = 0 /* DocumentState.SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */ convertToNoDocument(e) {\n return this.version = e, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , \n this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , \n this;\n }\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */ convertToUnknownDocument(e) {\n return this.version = e, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , \n this;\n }\n setHasCommittedMutations() {\n return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;\n }\n setHasLocalMutations() {\n return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), \n this;\n }\n setReadTime(e) {\n return this.readTime = e, this;\n }\n get hasLocalMutations() {\n return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;\n }\n get hasCommittedMutations() {\n return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;\n }\n get hasPendingWrites() {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n isValidDocument() {\n return 0 /* DocumentType.INVALID */ !== this.documentType;\n }\n isFoundDocument() {\n return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;\n }\n isNoDocument() {\n return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;\n }\n isUnknownDocument() {\n return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;\n }\n isEqual(e) {\n return e instanceof MutableDocument && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data);\n }\n mutableCopy() {\n return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);\n }\n toString() {\n return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nclass Bound {\n constructor(e, t) {\n this.position = e, this.inclusive = t;\n }\n}\n\nfunction __PRIVATE_boundCompareToDocument(e, t, n) {\n let r = 0;\n for (let i = 0; i < e.position.length; i++) {\n const s = t[i], o = e.position[i];\n if (s.field.isKeyField()) r = DocumentKey.comparator(DocumentKey.fromName(o.referenceValue), n.key); else {\n r = __PRIVATE_valueCompare(o, n.data.field(s.field));\n }\n if (\"desc\" /* Direction.DESCENDING */ === s.dir && (r *= -1), 0 !== r) break;\n }\n return r;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */ function __PRIVATE_boundEquals(e, t) {\n if (null === e) return null === t;\n if (null === t) return !1;\n if (e.inclusive !== t.inclusive || e.position.length !== t.position.length) return !1;\n for (let n = 0; n < e.position.length; n++) {\n if (!__PRIVATE_valueEquals(e.position[n], t.position[n])) return !1;\n }\n return !0;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */ class OrderBy {\n constructor(e, t = \"asc\" /* Direction.ASCENDING */) {\n this.field = e, this.dir = t;\n }\n}\n\nfunction __PRIVATE_orderByEquals(e, t) {\n return e.dir === t.dir && e.field.isEqual(t.field);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Filter {}\n\nclass FieldFilter extends Filter {\n constructor(e, t, n) {\n super(), this.field = e, this.op = t, this.value = n;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(e, t, n) {\n return e.isKeyField() ? \"in\" /* Operator.IN */ === t || \"not-in\" /* Operator.NOT_IN */ === t ? this.createKeyFieldInFilter(e, t, n) : new __PRIVATE_KeyFieldFilter(e, t, n) : \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t ? new __PRIVATE_ArrayContainsFilter(e, n) : \"in\" /* Operator.IN */ === t ? new __PRIVATE_InFilter(e, n) : \"not-in\" /* Operator.NOT_IN */ === t ? new __PRIVATE_NotInFilter(e, n) : \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t ? new __PRIVATE_ArrayContainsAnyFilter(e, n) : new FieldFilter(e, t, n);\n }\n static createKeyFieldInFilter(e, t, n) {\n return \"in\" /* Operator.IN */ === t ? new __PRIVATE_KeyFieldInFilter(e, n) : new __PRIVATE_KeyFieldNotInFilter(e, n);\n }\n matches(e) {\n const t = e.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n return \"!=\" /* Operator.NOT_EQUAL */ === this.op ? null !== t && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)) : null !== t && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t) && this.matchesComparison(__PRIVATE_valueCompare(t, this.value));\n // Only compare types with matching backend order (such as double and int).\n }\n matchesComparison(e) {\n switch (this.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n return e < 0;\n\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n return e <= 0;\n\n case \"==\" /* Operator.EQUAL */ :\n return 0 === e;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return 0 !== e;\n\n case \">\" /* Operator.GREATER_THAN */ :\n return e > 0;\n\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n return e >= 0;\n\n default:\n return fail();\n }\n }\n isInequality() {\n return [ \"<\" /* Operator.LESS_THAN */ , \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ , \">\" /* Operator.GREATER_THAN */ , \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ , \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;\n }\n getFlattenedFilters() {\n return [ this ];\n }\n getFilters() {\n return [ this ];\n }\n}\n\nclass CompositeFilter extends Filter {\n constructor(e, t) {\n super(), this.filters = e, this.op = t, this.ae = null;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(e, t) {\n return new CompositeFilter(e, t);\n }\n matches(e) {\n return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t => !t.matches(e))) : void 0 !== this.filters.find((t => t.matches(e)));\n }\n getFlattenedFilters() {\n return null !== this.ae || (this.ae = this.filters.reduce(((e, t) => e.concat(t.getFlattenedFilters())), [])), \n this.ae;\n }\n // Returns a mutable copy of `this.filters`\n getFilters() {\n return Object.assign([], this.filters);\n }\n}\n\nfunction __PRIVATE_compositeFilterIsConjunction(e) {\n return \"and\" /* CompositeOperator.AND */ === e.op;\n}\n\nfunction __PRIVATE_compositeFilterIsDisjunction(e) {\n return \"or\" /* CompositeOperator.OR */ === e.op;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */ function __PRIVATE_compositeFilterIsFlatConjunction(e) {\n return __PRIVATE_compositeFilterIsFlat(e) && __PRIVATE_compositeFilterIsConjunction(e);\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */ function __PRIVATE_compositeFilterIsFlat(e) {\n for (const t of e.filters) if (t instanceof CompositeFilter) return !1;\n return !0;\n}\n\nfunction __PRIVATE_canonifyFilter(e) {\n if (e instanceof FieldFilter) \n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return e.field.canonicalString() + e.op.toString() + canonicalId(e.value);\n if (__PRIVATE_compositeFilterIsFlatConjunction(e)) \n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\");\n {\n // filter instanceof CompositeFilter\n const t = e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\");\n return `${e.op}(${t})`;\n }\n}\n\nfunction __PRIVATE_filterEquals(e, t) {\n return e instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(e, t) {\n return t instanceof FieldFilter && e.op === t.op && e.field.isEqual(t.field) && __PRIVATE_valueEquals(e.value, t.value);\n }(e, t) : e instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(e, t) {\n if (t instanceof CompositeFilter && e.op === t.op && e.filters.length === t.filters.length) {\n return e.filters.reduce(((e, n, r) => e && __PRIVATE_filterEquals(n, t.filters[r])), !0);\n }\n return !1;\n }\n /**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */ (e, t) : void fail();\n}\n\nfunction __PRIVATE_compositeFilterWithAddedFilters(e, t) {\n const n = e.filters.concat(t);\n return CompositeFilter.create(n, e.op);\n}\n\n/** Returns a debug description for `filter`. */ function __PRIVATE_stringifyFilter(e) {\n return e instanceof FieldFilter ? function __PRIVATE_stringifyFieldFilter(e) {\n return `${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`;\n }\n /** Filter that matches on key fields (i.e. '__name__'). */ (e) : e instanceof CompositeFilter ? function __PRIVATE_stringifyCompositeFilter(e) {\n return e.op.toString() + \" {\" + e.getFilters().map(__PRIVATE_stringifyFilter).join(\" ,\") + \"}\";\n }(e) : \"Filter\";\n}\n\nclass __PRIVATE_KeyFieldFilter extends FieldFilter {\n constructor(e, t, n) {\n super(e, t, n), this.key = DocumentKey.fromName(n.referenceValue);\n }\n matches(e) {\n const t = DocumentKey.comparator(e.key, this.key);\n return this.matchesComparison(t);\n }\n}\n\n/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"in\" /* Operator.IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue(\"in\" /* Operator.IN */ , t);\n }\n matches(e) {\n return this.keys.some((t => t.isEqual(e.key)));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"not-in\" /* Operator.NOT_IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue(\"not-in\" /* Operator.NOT_IN */ , t);\n }\n matches(e) {\n return !this.keys.some((t => t.isEqual(e.key)));\n }\n}\n\nfunction __PRIVATE_extractDocumentKeysFromArrayValue(e, t) {\n var n;\n return ((null === (n = t.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((e => DocumentKey.fromName(e.referenceValue)));\n}\n\n/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"array-contains\" /* Operator.ARRAY_CONTAINS */ , t);\n }\n matches(e) {\n const t = e.data.field(this.field);\n return isArray(t) && __PRIVATE_arrayValueContains(t.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"in\" /* Operator.IN */ , t);\n }\n matches(e) {\n const t = e.data.field(this.field);\n return null !== t && __PRIVATE_arrayValueContains(this.value.arrayValue, t);\n }\n}\n\n/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"not-in\" /* Operator.NOT_IN */ , t);\n }\n matches(e) {\n if (__PRIVATE_arrayValueContains(this.value.arrayValue, {\n nullValue: \"NULL_VALUE\"\n })) return !1;\n const t = e.data.field(this.field);\n return null !== t && !__PRIVATE_arrayValueContains(this.value.arrayValue, t);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , t);\n }\n matches(e) {\n const t = e.data.field(this.field);\n return !(!isArray(t) || !t.arrayValue.values) && t.arrayValue.values.some((e => __PRIVATE_arrayValueContains(this.value.arrayValue, e)));\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Visible for testing\nclass __PRIVATE_TargetImpl {\n constructor(e, t = null, n = [], r = [], i = null, s = null, o = null) {\n this.path = e, this.collectionGroup = t, this.orderBy = n, this.filters = r, this.limit = i, \n this.startAt = s, this.endAt = o, this.ue = null;\n }\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */ function __PRIVATE_newTarget(e, t = null, n = [], r = [], i = null, s = null, o = null) {\n return new __PRIVATE_TargetImpl(e, t, n, r, i, s, o);\n}\n\nfunction __PRIVATE_canonifyTarget(e) {\n const t = __PRIVATE_debugCast(e);\n if (null === t.ue) {\n let e = t.path.canonicalString();\n null !== t.collectionGroup && (e += \"|cg:\" + t.collectionGroup), e += \"|f:\", e += t.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\"), \n e += \"|ob:\", e += t.orderBy.map((e => function __PRIVATE_canonifyOrderBy(e) {\n // TODO(b/29183165): Make this collision robust.\n return e.field.canonicalString() + e.dir;\n }(e))).join(\",\"), __PRIVATE_isNullOrUndefined(t.limit) || (e += \"|l:\", e += t.limit), \n t.startAt && (e += \"|lb:\", e += t.startAt.inclusive ? \"b:\" : \"a:\", e += t.startAt.position.map((e => canonicalId(e))).join(\",\")), \n t.endAt && (e += \"|ub:\", e += t.endAt.inclusive ? \"a:\" : \"b:\", e += t.endAt.position.map((e => canonicalId(e))).join(\",\")), \n t.ue = e;\n }\n return t.ue;\n}\n\nfunction __PRIVATE_targetEquals(e, t) {\n if (e.limit !== t.limit) return !1;\n if (e.orderBy.length !== t.orderBy.length) return !1;\n for (let n = 0; n < e.orderBy.length; n++) if (!__PRIVATE_orderByEquals(e.orderBy[n], t.orderBy[n])) return !1;\n if (e.filters.length !== t.filters.length) return !1;\n for (let n = 0; n < e.filters.length; n++) if (!__PRIVATE_filterEquals(e.filters[n], t.filters[n])) return !1;\n return e.collectionGroup === t.collectionGroup && (!!e.path.isEqual(t.path) && (!!__PRIVATE_boundEquals(e.startAt, t.startAt) && __PRIVATE_boundEquals(e.endAt, t.endAt)));\n}\n\nfunction __PRIVATE_targetIsDocumentTarget(e) {\n return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;\n}\n\n/** Returns the field filters that target the given field path. */ function __PRIVATE_targetGetFieldFiltersForPath(e, t) {\n return e.filters.filter((e => e instanceof FieldFilter && e.field.isEqual(t)));\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction __PRIVATE_targetGetAscendingBound(e, t, n) {\n let r = ie, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {\n let e = ie, t = !0;\n switch (n.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n e = __PRIVATE_valuesGetLowerBound(n.value);\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n e = n.value;\n break;\n\n case \">\" /* Operator.GREATER_THAN */ :\n e = n.value, t = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n e = ie;\n // Remaining filters cannot be used as lower bounds.\n }\n __PRIVATE_lowerBoundCompare({\n value: r,\n inclusive: i\n }, {\n value: e,\n inclusive: t\n }) < 0 && (r = e, i = t);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {\n if (e.orderBy[s].field.isEqual(t)) {\n const e = n.position[s];\n __PRIVATE_lowerBoundCompare({\n value: r,\n inclusive: i\n }, {\n value: e,\n inclusive: n.inclusive\n }) < 0 && (r = e, i = n.inclusive);\n break;\n }\n }\n return {\n value: r,\n inclusive: i\n };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */ function __PRIVATE_targetGetDescendingBound(e, t, n) {\n let r = re, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {\n let e = re, t = !0;\n switch (n.op) {\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n case \">\" /* Operator.GREATER_THAN */ :\n e = __PRIVATE_valuesGetUpperBound(n.value), t = !1;\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n e = n.value;\n break;\n\n case \"<\" /* Operator.LESS_THAN */ :\n e = n.value, t = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n e = re;\n // Remaining filters cannot be used as upper bounds.\n }\n __PRIVATE_upperBoundCompare({\n value: r,\n inclusive: i\n }, {\n value: e,\n inclusive: t\n }) > 0 && (r = e, i = t);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {\n if (e.orderBy[s].field.isEqual(t)) {\n const e = n.position[s];\n __PRIVATE_upperBoundCompare({\n value: r,\n inclusive: i\n }, {\n value: e,\n inclusive: n.inclusive\n }) > 0 && (r = e, i = n.inclusive);\n break;\n }\n }\n return {\n value: r,\n inclusive: i\n };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nclass __PRIVATE_QueryImpl {\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(e, t = null, n = [], r = [], i = null, s = \"F\" /* LimitType.First */ , o = null, _ = null) {\n this.path = e, this.collectionGroup = t, this.explicitOrderBy = n, this.filters = r, \n this.limit = i, this.limitType = s, this.startAt = o, this.endAt = _, this.ce = null, \n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n this.le = null, \n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n this.he = null, this.startAt, this.endAt;\n }\n}\n\n/** Creates a new Query instance with the options provided. */ function __PRIVATE_newQuery(e, t, n, r, i, s, o, _) {\n return new __PRIVATE_QueryImpl(e, t, n, r, i, s, o, _);\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */ function __PRIVATE_newQueryForPath(e) {\n return new __PRIVATE_QueryImpl(e);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nfunction __PRIVATE_queryMatchesAllDocuments(e) {\n return 0 === e.filters.length && null === e.limit && null == e.startAt && null == e.endAt && (0 === e.explicitOrderBy.length || 1 === e.explicitOrderBy.length && e.explicitOrderBy[0].field.isKeyField());\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nfunction __PRIVATE_isCollectionGroupQuery(e) {\n return null !== e.collectionGroup;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */ function __PRIVATE_queryNormalizedOrderBy(e) {\n const t = __PRIVATE_debugCast(e);\n if (null === t.ce) {\n t.ce = [];\n const e = new Set;\n // Any explicit order by fields should be added as is.\n for (const n of t.explicitOrderBy) t.ce.push(n), e.add(n.field.canonicalString());\n // The order of the implicit ordering always matches the last explicit order by.\n const n = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : \"asc\" /* Direction.ASCENDING */ , r = function __PRIVATE_getInequalityFilterFields(e) {\n let t = new SortedSet(FieldPath$1.comparator);\n return e.filters.forEach((e => {\n e.getFlattenedFilters().forEach((e => {\n e.isInequality() && (t = t.add(e.field));\n }));\n })), t;\n }\n /**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */ (t);\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n r.forEach((r => {\n e.has(r.canonicalString()) || r.isKeyField() || t.ce.push(new OrderBy(r, n));\n })), \n // Add the document key field to the last if it is not explicitly ordered.\n e.has(FieldPath$1.keyField().canonicalString()) || t.ce.push(new OrderBy(FieldPath$1.keyField(), n));\n }\n return t.ce;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */ function __PRIVATE_queryToTarget(e) {\n const t = __PRIVATE_debugCast(e);\n return t.le || (t.le = __PRIVATE__queryToTarget(t, __PRIVATE_queryNormalizedOrderBy(e))), \n t.le;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */ function __PRIVATE_queryToAggregateTarget(e) {\n const t = __PRIVATE_debugCast(e);\n return t.he || (\n // Do not include implicit order-bys for aggregate queries.\n t.he = __PRIVATE__queryToTarget(t, e.explicitOrderBy)), t.he;\n}\n\nfunction __PRIVATE__queryToTarget(e, t) {\n if (\"F\" /* LimitType.First */ === e.limitType) return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, e.startAt, e.endAt);\n {\n // Flip the orderBy directions since we want the last results\n t = t.map((e => {\n const t = \"desc\" /* Direction.DESCENDING */ === e.dir ? \"asc\" /* Direction.ASCENDING */ : \"desc\" /* Direction.DESCENDING */;\n return new OrderBy(e.field, t);\n }));\n // We need to swap the cursors to match the now-flipped query ordering.\n const n = e.endAt ? new Bound(e.endAt.position, e.endAt.inclusive) : null, r = e.startAt ? new Bound(e.startAt.position, e.startAt.inclusive) : null;\n // Now return as a LimitType.First query.\n return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, n, r);\n }\n}\n\nfunction __PRIVATE_queryWithAddedFilter(e, t) {\n const n = e.filters.concat([ t ]);\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), n, e.limit, e.limitType, e.startAt, e.endAt);\n}\n\nfunction __PRIVATE_queryWithLimit(e, t, n) {\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), t, n, e.startAt, e.endAt);\n}\n\nfunction __PRIVATE_queryEquals(e, t) {\n return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e), __PRIVATE_queryToTarget(t)) && e.limitType === t.limitType;\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nfunction __PRIVATE_canonifyQuery(e) {\n return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`;\n}\n\nfunction __PRIVATE_stringifyQuery(e) {\n return `Query(target=${function __PRIVATE_stringifyTarget(e) {\n let t = e.path.canonicalString();\n return null !== e.collectionGroup && (t += \" collectionGroup=\" + e.collectionGroup), \n e.filters.length > 0 && (t += `, filters: [${e.filters.map((e => __PRIVATE_stringifyFilter(e))).join(\", \")}]`), \n __PRIVATE_isNullOrUndefined(e.limit) || (t += \", limit: \" + e.limit), e.orderBy.length > 0 && (t += `, orderBy: [${e.orderBy.map((e => function __PRIVATE_stringifyOrderBy(e) {\n return `${e.field.canonicalString()} (${e.dir})`;\n }(e))).join(\", \")}]`), e.startAt && (t += \", startAt: \", t += e.startAt.inclusive ? \"b:\" : \"a:\", \n t += e.startAt.position.map((e => canonicalId(e))).join(\",\")), e.endAt && (t += \", endAt: \", \n t += e.endAt.inclusive ? \"a:\" : \"b:\", t += e.endAt.position.map((e => canonicalId(e))).join(\",\")), \n `Target(${t})`;\n }(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */ function __PRIVATE_queryMatches(e, t) {\n return t.isFoundDocument() && function __PRIVATE_queryMatchesPathAndCollectionGroup(e, t) {\n const n = t.key.path;\n return null !== e.collectionGroup ? t.key.hasCollectionId(e.collectionGroup) && e.path.isPrefixOf(n) : DocumentKey.isDocumentKey(e.path) ? e.path.isEqual(n) : e.path.isImmediateParentOf(n);\n }\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */ (e, t) && function __PRIVATE_queryMatchesOrderBy(e, t) {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const n of __PRIVATE_queryNormalizedOrderBy(e)) \n // order-by key always matches\n if (!n.field.isKeyField() && null === t.data.field(n.field)) return !1;\n return !0;\n }(e, t) && function __PRIVATE_queryMatchesFilters(e, t) {\n for (const n of e.filters) if (!n.matches(t)) return !1;\n return !0;\n }\n /** Makes sure a document is within the bounds, if provided. */ (e, t) && function __PRIVATE_queryMatchesBounds(e, t) {\n if (e.startAt && !\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n function __PRIVATE_boundSortsBeforeDocument(e, t, n) {\n const r = __PRIVATE_boundCompareToDocument(e, t, n);\n return e.inclusive ? r <= 0 : r < 0;\n }(e.startAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1;\n if (e.endAt && !function __PRIVATE_boundSortsAfterDocument(e, t, n) {\n const r = __PRIVATE_boundCompareToDocument(e, t, n);\n return e.inclusive ? r >= 0 : r > 0;\n }(e.endAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1;\n return !0;\n }\n /**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */ (e, t);\n}\n\nfunction __PRIVATE_queryCollectionGroup(e) {\n return e.collectionGroup || (e.path.length % 2 == 1 ? e.path.lastSegment() : e.path.get(e.path.length - 2));\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */ function __PRIVATE_newQueryComparator(e) {\n return (t, n) => {\n let r = !1;\n for (const i of __PRIVATE_queryNormalizedOrderBy(e)) {\n const e = __PRIVATE_compareDocs(i, t, n);\n if (0 !== e) return e;\n r = r || i.field.isKeyField();\n }\n return 0;\n };\n}\n\nfunction __PRIVATE_compareDocs(e, t, n) {\n const r = e.field.isKeyField() ? DocumentKey.comparator(t.key, n.key) : function __PRIVATE_compareDocumentsByField(e, t, n) {\n const r = t.data.field(e), i = n.data.field(e);\n return null !== r && null !== i ? __PRIVATE_valueCompare(r, i) : fail();\n }(e.field, t, n);\n switch (e.dir) {\n case \"asc\" /* Direction.ASCENDING */ :\n return r;\n\n case \"desc\" /* Direction.DESCENDING */ :\n return -1 * r;\n\n default:\n return fail();\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */ class ObjectMap {\n constructor(e, t) {\n this.mapKeyFn = e, this.equalsFn = t, \n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n this.inner = {}, \n /** The number of entries stored in the map */\n this.innerSize = 0;\n }\n /** Get a value for this key, or undefined if it does not exist. */ get(e) {\n const t = this.mapKeyFn(e), n = this.inner[t];\n if (void 0 !== n) for (const [t, r] of n) if (this.equalsFn(t, e)) return r;\n }\n has(e) {\n return void 0 !== this.get(e);\n }\n /** Put this key and value in the map. */ set(e, t) {\n const n = this.mapKeyFn(e), r = this.inner[n];\n if (void 0 === r) return this.inner[n] = [ [ e, t ] ], void this.innerSize++;\n for (let n = 0; n < r.length; n++) if (this.equalsFn(r[n][0], e)) \n // This is updating an existing entry and does not increase `innerSize`.\n return void (r[n] = [ e, t ]);\n r.push([ e, t ]), this.innerSize++;\n }\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */ delete(e) {\n const t = this.mapKeyFn(e), n = this.inner[t];\n if (void 0 === n) return !1;\n for (let r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], e)) return 1 === n.length ? delete this.inner[t] : n.splice(r, 1), \n this.innerSize--, !0;\n return !1;\n }\n forEach(e) {\n forEach(this.inner, ((t, n) => {\n for (const [t, r] of n) e(t, r);\n }));\n }\n isEmpty() {\n return isEmpty(this.inner);\n }\n size() {\n return this.innerSize;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const oe = new SortedMap(DocumentKey.comparator);\n\nfunction __PRIVATE_mutableDocumentMap() {\n return oe;\n}\n\nconst _e = new SortedMap(DocumentKey.comparator);\n\nfunction documentMap(...e) {\n let t = _e;\n for (const n of e) t = t.insert(n.key, n);\n return t;\n}\n\nfunction __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) {\n let t = _e;\n return e.forEach(((e, n) => t = t.insert(e, n.overlayedDocument))), t;\n}\n\nfunction __PRIVATE_newOverlayMap() {\n return __PRIVATE_newDocumentKeyMap();\n}\n\nfunction __PRIVATE_newMutationMap() {\n return __PRIVATE_newDocumentKeyMap();\n}\n\nfunction __PRIVATE_newDocumentKeyMap() {\n return new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t)));\n}\n\nconst ae = new SortedMap(DocumentKey.comparator);\n\nconst ue = new SortedSet(DocumentKey.comparator);\n\nfunction __PRIVATE_documentKeySet(...e) {\n let t = ue;\n for (const n of e) t = t.add(n);\n return t;\n}\n\nconst ce = new SortedSet(__PRIVATE_primitiveComparator);\n\nfunction __PRIVATE_targetIdSet() {\n return ce;\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 * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */ function __PRIVATE_toDouble(e, t) {\n if (e.useProto3Json) {\n if (isNaN(t)) return {\n doubleValue: \"NaN\"\n };\n if (t === 1 / 0) return {\n doubleValue: \"Infinity\"\n };\n if (t === -1 / 0) return {\n doubleValue: \"-Infinity\"\n };\n }\n return {\n doubleValue: __PRIVATE_isNegativeZero(t) ? \"-0\" : t\n };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */ function __PRIVATE_toInteger(e) {\n return {\n integerValue: \"\" + e\n };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */ function toNumber(e, t) {\n return isSafeInteger(t) ? __PRIVATE_toInteger(t) : __PRIVATE_toDouble(e, t);\n}\n\n/**\n * @license\n * Copyright 2018 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/** Used to represent a field transform on a mutation. */ class TransformOperation {\n constructor() {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n this._ = void 0;\n }\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */ function __PRIVATE_applyTransformOperationToLocalView(e, t, n) {\n return e instanceof __PRIVATE_ServerTimestampTransform ? function serverTimestamp$1(e, t) {\n const n = {\n fields: {\n __type__: {\n stringValue: \"server_timestamp\"\n },\n __local_write_time__: {\n timestampValue: {\n seconds: e.seconds,\n nanos: e.nanoseconds\n }\n }\n }\n };\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n return t && __PRIVATE_isServerTimestamp(t) && (t = __PRIVATE_getPreviousValue(t)), \n t && (n.fields.__previous_value__ = t), {\n mapValue: n\n };\n }(n, t) : e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e, t) {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const n = __PRIVATE_computeTransformOperationBaseValue(e, t), r = asNumber(n) + asNumber(e.Pe);\n return isInteger(n) && isInteger(e.Pe) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e.serializer, r);\n }(e, t);\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */ function __PRIVATE_applyTransformOperationToRemoteDocument(e, t, n) {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n return e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : n;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */ function __PRIVATE_computeTransformOperationBaseValue(e, t) {\n return e instanceof __PRIVATE_NumericIncrementTransformOperation ? \n /** Returns true if `value` is either an IntegerValue or a DoubleValue. */\n function __PRIVATE_isNumber(e) {\n return isInteger(e) || function __PRIVATE_isDouble(e) {\n return !!e && \"doubleValue\" in e;\n }(e);\n }(t) ? t : {\n integerValue: 0\n } : null;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nclass __PRIVATE_ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation {\n constructor(e) {\n super(), this.elements = e;\n }\n}\n\nfunction __PRIVATE_applyArrayUnionTransformOperation(e, t) {\n const n = __PRIVATE_coercedFieldValuesArray(t);\n for (const t of e.elements) n.some((e => __PRIVATE_valueEquals(e, t))) || n.push(t);\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation {\n constructor(e) {\n super(), this.elements = e;\n }\n}\n\nfunction __PRIVATE_applyArrayRemoveTransformOperation(e, t) {\n let n = __PRIVATE_coercedFieldValuesArray(t);\n for (const t of e.elements) n = n.filter((e => !__PRIVATE_valueEquals(e, t)));\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation {\n constructor(e, t) {\n super(), this.serializer = e, this.Pe = t;\n }\n}\n\nfunction asNumber(e) {\n return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);\n}\n\nfunction __PRIVATE_coercedFieldValuesArray(e) {\n return isArray(e) && e.arrayValue.values ? e.arrayValue.values.slice() : [];\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A field path and the TransformOperation to perform upon it. */ class FieldTransform {\n constructor(e, t) {\n this.field = e, this.transform = t;\n }\n}\n\nfunction __PRIVATE_fieldTransformEquals(e, t) {\n return e.field.isEqual(t.field) && function __PRIVATE_transformOperationEquals(e, t) {\n return e instanceof __PRIVATE_ArrayUnionTransformOperation && t instanceof __PRIVATE_ArrayUnionTransformOperation || e instanceof __PRIVATE_ArrayRemoveTransformOperation && t instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_arrayEquals(e.elements, t.elements, __PRIVATE_valueEquals) : e instanceof __PRIVATE_NumericIncrementTransformOperation && t instanceof __PRIVATE_NumericIncrementTransformOperation ? __PRIVATE_valueEquals(e.Pe, t.Pe) : e instanceof __PRIVATE_ServerTimestampTransform && t instanceof __PRIVATE_ServerTimestampTransform;\n }(e.transform, t.transform);\n}\n\n/** The result of successfully applying a mutation to the backend. */\nclass MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n e, \n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n t) {\n this.version = e, this.transformResults = t;\n }\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */ class Precondition {\n constructor(e, t) {\n this.updateTime = e, this.exists = t;\n }\n /** Creates a new empty Precondition. */ static none() {\n return new Precondition;\n }\n /** Creates a new Precondition with an exists flag. */ static exists(e) {\n return new Precondition(void 0, e);\n }\n /** Creates a new Precondition based on a version a document exists at. */ static updateTime(e) {\n return new Precondition(e);\n }\n /** Returns whether this Precondition is empty. */ get isNone() {\n return void 0 === this.updateTime && void 0 === this.exists;\n }\n isEqual(e) {\n return this.exists === e.exists && (this.updateTime ? !!e.updateTime && this.updateTime.isEqual(e.updateTime) : !e.updateTime);\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */ function __PRIVATE_preconditionIsValidForDocument(e, t) {\n return void 0 !== e.updateTime ? t.isFoundDocument() && t.version.isEqual(e.updateTime) : void 0 === e.exists || e.exists === t.isFoundDocument();\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */ class Mutation {}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */ function __PRIVATE_calculateOverlayMutation(e, t) {\n if (!e.hasLocalMutations || t && 0 === t.fields.length) return null;\n // mask is null when sets or deletes are applied to the current document.\n if (null === t) return e.isNoDocument() ? new __PRIVATE_DeleteMutation(e.key, Precondition.none()) : new __PRIVATE_SetMutation(e.key, e.data, Precondition.none());\n {\n const n = e.data, r = ObjectValue.empty();\n let i = new SortedSet(FieldPath$1.comparator);\n for (let e of t.fields) if (!i.has(e)) {\n let t = n.field(e);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n null === t && e.length > 1 && (e = e.popLast(), t = n.field(e)), null === t ? r.delete(e) : r.set(e, t), \n i = i.add(e);\n }\n return new __PRIVATE_PatchMutation(e.key, r, new FieldMask(i.toArray()), Precondition.none());\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */ function __PRIVATE_mutationApplyToRemoteDocument(e, t, n) {\n e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToRemoteDocument(e, t, n) {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const r = e.value.clone(), i = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults);\n r.setAll(i), t.convertToFoundDocument(n.version, r).setHasCommittedMutations();\n }(e, t, n) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToRemoteDocument(e, t, n) {\n if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) \n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n return void t.convertToUnknownDocument(n.version);\n const r = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults), i = t.data;\n i.setAll(__PRIVATE_getPatch(e)), i.setAll(r), t.convertToFoundDocument(n.version, i).setHasCommittedMutations();\n }(e, t, n) : function __PRIVATE_deleteMutationApplyToRemoteDocument(e, t, n) {\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n t.convertToNoDocument(n.version).setHasCommittedMutations();\n }(0, t, n);\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */ function __PRIVATE_mutationApplyToLocalView(e, t, n, r) {\n return e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToLocalView(e, t, n, r) {\n if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) \n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return n;\n const i = e.value.clone(), s = __PRIVATE_localTransformResults(e.fieldTransforms, r, t);\n return i.setAll(s), t.convertToFoundDocument(t.version, i).setHasLocalMutations(), \n null;\n // SetMutation overwrites all fields.\n }\n /**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */ (e, t, n, r) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToLocalView(e, t, n, r) {\n if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return n;\n const i = __PRIVATE_localTransformResults(e.fieldTransforms, r, t), s = t.data;\n if (s.setAll(__PRIVATE_getPatch(e)), s.setAll(i), t.convertToFoundDocument(t.version, s).setHasLocalMutations(), \n null === n) return null;\n return n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e => e.field)));\n }\n /**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */ (e, t, n, r) : function __PRIVATE_deleteMutationApplyToLocalView(e, t, n) {\n if (__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return t.convertToNoDocument(t.version).setHasLocalMutations(), \n null;\n return n;\n }\n /**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */ (e, t, n);\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */ function __PRIVATE_mutationExtractBaseValue(e, t) {\n let n = null;\n for (const r of e.fieldTransforms) {\n const e = t.data.field(r.field), i = __PRIVATE_computeTransformOperationBaseValue(r.transform, e || null);\n null != i && (null === n && (n = ObjectValue.empty()), n.set(r.field, i));\n }\n return n || null;\n}\n\nfunction __PRIVATE_mutationEquals(e, t) {\n return e.type === t.type && (!!e.key.isEqual(t.key) && (!!e.precondition.isEqual(t.precondition) && (!!function __PRIVATE_fieldTransformsAreEqual(e, t) {\n return void 0 === e && void 0 === t || !(!e || !t) && __PRIVATE_arrayEquals(e, t, ((e, t) => __PRIVATE_fieldTransformEquals(e, t)));\n }(e.fieldTransforms, t.fieldTransforms) && (0 /* MutationType.Set */ === e.type ? e.value.isEqual(t.value) : 1 /* MutationType.Patch */ !== e.type || e.data.isEqual(t.data) && e.fieldMask.isEqual(t.fieldMask)))));\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */ class __PRIVATE_SetMutation extends Mutation {\n constructor(e, t, n, r = []) {\n super(), this.key = e, this.value = t, this.precondition = n, this.fieldTransforms = r, \n this.type = 0 /* MutationType.Set */;\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass __PRIVATE_PatchMutation extends Mutation {\n constructor(e, t, n, r, i = []) {\n super(), this.key = e, this.data = t, this.fieldMask = n, this.precondition = r, \n this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;\n }\n getFieldMask() {\n return this.fieldMask;\n }\n}\n\nfunction __PRIVATE_getPatch(e) {\n const t = new Map;\n return e.fieldMask.fields.forEach((n => {\n if (!n.isEmpty()) {\n const r = e.data.field(n);\n t.set(n, r);\n }\n })), t;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */ function __PRIVATE_serverTransformResults(e, t, n) {\n const r = new Map;\n __PRIVATE_hardAssert(e.length === n.length);\n for (let i = 0; i < n.length; i++) {\n const s = e[i], o = s.transform, _ = t.data.field(s.field);\n r.set(s.field, __PRIVATE_applyTransformOperationToRemoteDocument(o, _, n[i]));\n }\n return r;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */ function __PRIVATE_localTransformResults(e, t, n) {\n const r = new Map;\n for (const i of e) {\n const e = i.transform, s = n.data.field(i.field);\n r.set(i.field, __PRIVATE_applyTransformOperationToLocalView(e, s, t));\n }\n return r;\n}\n\n/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation {\n constructor(e, t) {\n super(), this.key = e, this.precondition = t, this.type = 2 /* MutationType.Delete */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass __PRIVATE_VerifyMutation extends Mutation {\n constructor(e, t) {\n super(), this.key = e, this.precondition = t, this.type = 3 /* MutationType.Verify */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */ class MutationBatch {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(e, t, n, r) {\n this.batchId = e, this.localWriteTime = t, this.baseMutations = n, this.mutations = r;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */ applyToRemoteDocument(e, t) {\n const n = t.mutationResults;\n for (let t = 0; t < this.mutations.length; t++) {\n const r = this.mutations[t];\n if (r.key.isEqual(e.key)) {\n __PRIVATE_mutationApplyToRemoteDocument(r, e, n[t]);\n }\n }\n }\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */ applyToLocalView(e, t) {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const n of this.baseMutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));\n // Second, apply all user-provided mutations.\n for (const n of this.mutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));\n return t;\n }\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */ applyToLocalDocumentSet(e, t) {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const n = __PRIVATE_newMutationMap();\n return this.mutations.forEach((r => {\n const i = e.get(r.key), s = i.overlayedDocument;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n let o = this.applyToLocalView(s, i.mutatedFields);\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n o = t.has(r.key) ? null : o;\n const _ = __PRIVATE_calculateOverlayMutation(s, o);\n null !== _ && n.set(r.key, _), s.isValidDocument() || s.convertToNoDocument(SnapshotVersion.min());\n })), n;\n }\n keys() {\n return this.mutations.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet());\n }\n isEqual(e) {\n return this.batchId === e.batchId && __PRIVATE_arrayEquals(this.mutations, e.mutations, ((e, t) => __PRIVATE_mutationEquals(e, t))) && __PRIVATE_arrayEquals(this.baseMutations, e.baseMutations, ((e, t) => __PRIVATE_mutationEquals(e, t)));\n }\n}\n\n/** The result of applying a mutation batch to the backend. */ class MutationBatchResult {\n constructor(e, t, n, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n r) {\n this.batch = e, this.commitVersion = t, this.mutationResults = n, this.docVersions = r;\n }\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */ static from(e, t, n) {\n __PRIVATE_hardAssert(e.mutations.length === n.length);\n let r = function __PRIVATE_documentVersionMap() {\n return ae;\n }();\n const i = e.mutations;\n for (let e = 0; e < i.length; e++) r = r.insert(i[e].key, n[e].version);\n return new MutationBatchResult(e, t, n, r);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */ class Overlay {\n constructor(e, t) {\n this.largestBatchId = e, this.mutation = t;\n }\n getKey() {\n return this.mutation.key;\n }\n isEqual(e) {\n return null !== e && this.mutation === e.mutation;\n }\n toString() {\n return `Overlay{\\n largestBatchId: ${this.largestBatchId},\\n mutation: ${this.mutation.toString()}\\n }`;\n }\n}\n\n/**\n * @license\n * Copyright 2023 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 * Concrete implementation of the Aggregate type.\n */ class __PRIVATE_AggregateImpl {\n constructor(e, t, n) {\n this.alias = e, this.aggregateType = t, this.fieldPath = n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class ExistenceFilter {\n constructor(e, t) {\n this.count = e, this.unchangedNames = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */ var le, he;\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nfunction __PRIVATE_isPermanentError(e) {\n switch (e) {\n default:\n return fail();\n\n case D.CANCELLED:\n case D.UNKNOWN:\n case D.DEADLINE_EXCEEDED:\n case D.RESOURCE_EXHAUSTED:\n case D.INTERNAL:\n case D.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case D.UNAUTHENTICATED:\n return !1;\n\n case D.INVALID_ARGUMENT:\n case D.NOT_FOUND:\n case D.ALREADY_EXISTS:\n case D.PERMISSION_DENIED:\n case D.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependent on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case D.ABORTED:\n case D.OUT_OF_RANGE:\n case D.UNIMPLEMENTED:\n case D.DATA_LOSS:\n return !0;\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nfunction __PRIVATE_mapCodeFromRpcCode(e) {\n if (void 0 === e) \n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n return __PRIVATE_logError(\"GRPC error has no .code\"), D.UNKNOWN;\n switch (e) {\n case le.OK:\n return D.OK;\n\n case le.CANCELLED:\n return D.CANCELLED;\n\n case le.UNKNOWN:\n return D.UNKNOWN;\n\n case le.DEADLINE_EXCEEDED:\n return D.DEADLINE_EXCEEDED;\n\n case le.RESOURCE_EXHAUSTED:\n return D.RESOURCE_EXHAUSTED;\n\n case le.INTERNAL:\n return D.INTERNAL;\n\n case le.UNAVAILABLE:\n return D.UNAVAILABLE;\n\n case le.UNAUTHENTICATED:\n return D.UNAUTHENTICATED;\n\n case le.INVALID_ARGUMENT:\n return D.INVALID_ARGUMENT;\n\n case le.NOT_FOUND:\n return D.NOT_FOUND;\n\n case le.ALREADY_EXISTS:\n return D.ALREADY_EXISTS;\n\n case le.PERMISSION_DENIED:\n return D.PERMISSION_DENIED;\n\n case le.FAILED_PRECONDITION:\n return D.FAILED_PRECONDITION;\n\n case le.ABORTED:\n return D.ABORTED;\n\n case le.OUT_OF_RANGE:\n return D.OUT_OF_RANGE;\n\n case le.UNIMPLEMENTED:\n return D.UNIMPLEMENTED;\n\n case le.DATA_LOSS:\n return D.DATA_LOSS;\n\n default:\n return fail();\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */ (he = le || (le = {}))[he.OK = 0] = \"OK\", he[he.CANCELLED = 1] = \"CANCELLED\", \nhe[he.UNKNOWN = 2] = \"UNKNOWN\", he[he.INVALID_ARGUMENT = 3] = \"INVALID_ARGUMENT\", \nhe[he.DEADLINE_EXCEEDED = 4] = \"DEADLINE_EXCEEDED\", he[he.NOT_FOUND = 5] = \"NOT_FOUND\", \nhe[he.ALREADY_EXISTS = 6] = \"ALREADY_EXISTS\", he[he.PERMISSION_DENIED = 7] = \"PERMISSION_DENIED\", \nhe[he.UNAUTHENTICATED = 16] = \"UNAUTHENTICATED\", he[he.RESOURCE_EXHAUSTED = 8] = \"RESOURCE_EXHAUSTED\", \nhe[he.FAILED_PRECONDITION = 9] = \"FAILED_PRECONDITION\", he[he.ABORTED = 10] = \"ABORTED\", \nhe[he.OUT_OF_RANGE = 11] = \"OUT_OF_RANGE\", he[he.UNIMPLEMENTED = 12] = \"UNIMPLEMENTED\", \nhe[he.INTERNAL = 13] = \"INTERNAL\", he[he.UNAVAILABLE = 14] = \"UNAVAILABLE\", he[he.DATA_LOSS = 15] = \"DATA_LOSS\";\n\n/**\n * @license\n * Copyright 2023 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 * The global, singleton instance of TestingHooksSpi.\n *\n * This variable will be `null` in all cases _except_ when running from\n * integration tests that have registered callbacks to be notified of events\n * that happen during the test execution.\n */\nlet Pe = null;\n\n/**\n * Sets the value of the `testingHooksSpi` object.\n * @param instance the instance to set.\n */\n/**\n * @license\n * Copyright 2023 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 * An instance of the Platform's 'TextEncoder' implementation.\n */\nfunction __PRIVATE_newTextEncoder() {\n return new TextEncoder;\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst Ie = new Integer([ 4294967295, 4294967295 ], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction __PRIVATE_getMd5HashValue(e) {\n const t = __PRIVATE_newTextEncoder().encode(e), n = new Md5;\n return n.update(t), new Uint8Array(n.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2’s complement using little endian.\nfunction __PRIVATE_get64BitUints(e) {\n const t = new DataView(e.buffer), n = t.getUint32(0, /* littleEndian= */ !0), r = t.getUint32(4, /* littleEndian= */ !0), i = t.getUint32(8, /* littleEndian= */ !0), s = t.getUint32(12, /* littleEndian= */ !0);\n return [ new Integer([ n, r ], 0), new Integer([ i, s ], 0) ];\n}\n\nclass BloomFilter {\n constructor(e, t, n) {\n if (this.bitmap = e, this.padding = t, this.hashCount = n, t < 0 || t >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t}`);\n if (n < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);\n if (e.length > 0 && 0 === this.hashCount) \n // Only empty bloom filter can have 0 hash count.\n throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);\n if (0 === e.length && 0 !== t) \n // Empty bloom filter should have 0 padding.\n throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t}`);\n this.Ie = 8 * e.length - t, \n // Set the bit count in Integer to avoid repetition in mightContain().\n this.Te = Integer.fromNumber(this.Ie);\n }\n // Calculate the ith hash value based on the hashed 64bit integers,\n // and calculate its corresponding bit index in the bitmap to be checked.\n Ee(e, t, n) {\n // Calculate hashed value h(i) = h1 + (i * h2).\n let r = e.add(t.multiply(Integer.fromNumber(n)));\n // Wrap if hash value overflow 64bit.\n return 1 === r.compare(Ie) && (r = new Integer([ r.getBits(0), r.getBits(1) ], 0)), \n r.modulo(this.Te).toNumber();\n }\n // Return whether the bit on the given index in the bitmap is set to 1.\n de(e) {\n return 0 != (this.bitmap[Math.floor(e / 8)] & 1 << e % 8);\n }\n mightContain(e) {\n // Empty bitmap should always return false on membership check.\n if (0 === this.Ie) return !1;\n const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);\n for (let e = 0; e < this.hashCount; e++) {\n const t = this.Ee(n, r, e);\n if (!this.de(t)) return !1;\n }\n return !0;\n }\n /** Create bloom filter for testing purposes only. */ static create(e, t, n) {\n const r = e % 8 == 0 ? 0 : 8 - e % 8, i = new Uint8Array(Math.ceil(e / 8)), s = new BloomFilter(i, r, t);\n return n.forEach((e => s.insert(e))), s;\n }\n insert(e) {\n if (0 === this.Ie) return;\n const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);\n for (let e = 0; e < this.hashCount; e++) {\n const t = this.Ee(n, r, e);\n this.Ae(t);\n }\n }\n Ae(e) {\n const t = Math.floor(e / 8), n = e % 8;\n this.bitmap[t] |= 1 << n;\n }\n}\n\nclass __PRIVATE_BloomFilterError extends Error {\n constructor() {\n super(...arguments), this.name = \"BloomFilterError\";\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */ class RemoteEvent {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n e, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n t, \n /**\n * A map of targets that is known to be inconsistent, and the purpose for\n * re-listening. Listens for these targets should be re-established without\n * resume tokens.\n */\n n, \n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n r, \n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n i) {\n this.snapshotVersion = e, this.targetChanges = t, this.targetMismatches = n, this.documentUpdates = r, \n this.resolvedLimboDocuments = i;\n }\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(e, t, n) {\n const r = new Map;\n return r.set(e, TargetChange.createSynthesizedTargetChangeForCurrentChange(e, t, n)), \n new RemoteEvent(SnapshotVersion.min(), r, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet());\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */ class TargetChange {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n e, \n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n t, \n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n n, \n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n r, \n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n i) {\n this.resumeToken = e, this.current = t, this.addedDocuments = n, this.modifiedDocuments = r, \n this.removedDocuments = i;\n }\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */ static createSynthesizedTargetChangeForCurrentChange(e, t, n) {\n return new TargetChange(n, t, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet());\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */ class __PRIVATE_DocumentWatchChange {\n constructor(\n /** The new document applies to all of these targets. */\n e, \n /** The new document is removed from all of these targets. */\n t, \n /** The key of the document for this change. */\n n, \n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n r) {\n this.Re = e, this.removedTargetIds = t, this.key = n, this.Ve = r;\n }\n}\n\nclass __PRIVATE_ExistenceFilterChange {\n constructor(e, t) {\n this.targetId = e, this.me = t;\n }\n}\n\nclass __PRIVATE_WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n e, \n /** The target IDs that were added/removed/set. */\n t, \n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n n = ByteString.EMPTY_BYTE_STRING\n /** An RPC error indicating why the watch failed. */ , r = null) {\n this.state = e, this.targetIds = t, this.resumeToken = n, this.cause = r;\n }\n}\n\n/** Tracks the internal state of a Watch target. */ class __PRIVATE_TargetState {\n constructor() {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n this.fe = 0, \n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n this.ge = __PRIVATE_snapshotChangesMap(), \n /** See public getters for explanations of these fields. */\n this.pe = ByteString.EMPTY_BYTE_STRING, this.ye = !1, \n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n this.we = !0;\n }\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */ get current() {\n return this.ye;\n }\n /** The last resume token sent to us for this target. */ get resumeToken() {\n return this.pe;\n }\n /** Whether this target has pending target adds or target removes. */ get Se() {\n return 0 !== this.fe;\n }\n /** Whether we have modified any state that should trigger a snapshot. */ get be() {\n return this.we;\n }\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */ De(e) {\n e.approximateByteSize() > 0 && (this.we = !0, this.pe = e);\n }\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */ ve() {\n let e = __PRIVATE_documentKeySet(), t = __PRIVATE_documentKeySet(), n = __PRIVATE_documentKeySet();\n return this.ge.forEach(((r, i) => {\n switch (i) {\n case 0 /* ChangeType.Added */ :\n e = e.add(r);\n break;\n\n case 2 /* ChangeType.Modified */ :\n t = t.add(r);\n break;\n\n case 1 /* ChangeType.Removed */ :\n n = n.add(r);\n break;\n\n default:\n fail();\n }\n })), new TargetChange(this.pe, this.ye, e, t, n);\n }\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */ Ce() {\n this.we = !1, this.ge = __PRIVATE_snapshotChangesMap();\n }\n Fe(e, t) {\n this.we = !0, this.ge = this.ge.insert(e, t);\n }\n Me(e) {\n this.we = !0, this.ge = this.ge.remove(e);\n }\n xe() {\n this.fe += 1;\n }\n Oe() {\n this.fe -= 1, __PRIVATE_hardAssert(this.fe >= 0);\n }\n Ne() {\n this.we = !0, this.ye = !0;\n }\n}\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nclass __PRIVATE_WatchChangeAggregator {\n constructor(e) {\n this.Le = e, \n /** The internal state of all tracked targets. */\n this.Be = new Map, \n /** Keeps track of the documents to update since the last raised snapshot. */\n this.ke = __PRIVATE_mutableDocumentMap(), \n /** A mapping of document keys to their set of target IDs. */\n this.qe = __PRIVATE_documentTargetMap(), \n /**\n * A map of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n this.Qe = new SortedMap(__PRIVATE_primitiveComparator);\n }\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */ Ke(e) {\n for (const t of e.Re) e.Ve && e.Ve.isFoundDocument() ? this.$e(t, e.Ve) : this.Ue(t, e.key, e.Ve);\n for (const t of e.removedTargetIds) this.Ue(t, e.key, e.Ve);\n }\n /** Processes and adds the WatchTargetChange to the current set of changes. */ We(e) {\n this.forEachTarget(e, (t => {\n const n = this.Ge(t);\n switch (e.state) {\n case 0 /* WatchTargetChangeState.NoChange */ :\n this.ze(t) && n.De(e.resumeToken);\n break;\n\n case 1 /* WatchTargetChangeState.Added */ :\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Oe(), n.Se || \n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n n.Ce(), n.De(e.resumeToken);\n break;\n\n case 2 /* WatchTargetChangeState.Removed */ :\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Oe(), n.Se || this.removeTarget(t);\n break;\n\n case 3 /* WatchTargetChangeState.Current */ :\n this.ze(t) && (n.Ne(), n.De(e.resumeToken));\n break;\n\n case 4 /* WatchTargetChangeState.Reset */ :\n this.ze(t) && (\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.je(t), n.De(e.resumeToken));\n break;\n\n default:\n fail();\n }\n }));\n }\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */ forEachTarget(e, t) {\n e.targetIds.length > 0 ? e.targetIds.forEach(t) : this.Be.forEach(((e, n) => {\n this.ze(n) && t(n);\n }));\n }\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */ He(e) {\n const t = e.targetId, n = e.me.count, r = this.Je(t);\n if (r) {\n const i = r.target;\n if (__PRIVATE_targetIsDocumentTarget(i)) if (0 === n) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const e = new DocumentKey(i.path);\n this.Ue(t, e, MutableDocument.newNoDocument(e, SnapshotVersion.min()));\n } else __PRIVATE_hardAssert(1 === n); else {\n const r = this.Ye(t);\n // Existence filter mismatch. Mark the documents as being in limbo, and\n // raise a snapshot with `isFromCache:true`.\n if (r !== n) {\n // Apply bloom filter to identify and mark removed documents.\n const n = this.Ze(e), i = n ? this.Xe(n, e, r) : 1 /* BloomFilterApplicationStatus.Skipped */;\n if (0 /* BloomFilterApplicationStatus.Success */ !== i) {\n // If bloom filter application fails, we reset the mapping and\n // trigger re-run of the query.\n this.je(t);\n const e = 2 /* BloomFilterApplicationStatus.FalsePositive */ === i ? \"TargetPurposeExistenceFilterMismatchBloom\" /* TargetPurpose.ExistenceFilterMismatchBloom */ : \"TargetPurposeExistenceFilterMismatch\" /* TargetPurpose.ExistenceFilterMismatch */;\n this.Qe = this.Qe.insert(t, e);\n }\n null == Pe || Pe.et(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e, t, n, r, i) {\n var s, o, _, a, u, c;\n const l = {\n localCacheCount: e,\n existenceFilterCount: t.count,\n databaseId: n.database,\n projectId: n.projectId\n }, h = t.unchangedNames;\n h && (l.bloomFilter = {\n applied: 0 /* BloomFilterApplicationStatus.Success */ === i,\n hashCount: null !== (s = null == h ? void 0 : h.hashCount) && void 0 !== s ? s : 0,\n bitmapLength: null !== (a = null === (_ = null === (o = null == h ? void 0 : h.bits) || void 0 === o ? void 0 : o.bitmap) || void 0 === _ ? void 0 : _.length) && void 0 !== a ? a : 0,\n padding: null !== (c = null === (u = null == h ? void 0 : h.bits) || void 0 === u ? void 0 : u.padding) && void 0 !== c ? c : 0,\n mightContain: e => {\n var t;\n return null !== (t = null == r ? void 0 : r.mightContain(e)) && void 0 !== t && t;\n }\n });\n return l;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (r, e.me, this.Le.tt(), n, i));\n }\n }\n }\n }\n /**\n * Parse the bloom filter from the \"unchanged_names\" field of an existence\n * filter.\n */ Ze(e) {\n const t = e.me.unchangedNames;\n if (!t || !t.bits) return null;\n const {bits: {bitmap: n = \"\", padding: r = 0}, hashCount: i = 0} = t;\n let s, o;\n try {\n s = __PRIVATE_normalizeByteString(n).toUint8Array();\n } catch (e) {\n if (e instanceof __PRIVATE_Base64DecodeError) return __PRIVATE_logWarn(\"Decoding the base64 bloom filter in existence filter failed (\" + e.message + \"); ignoring the bloom filter and falling back to full re-query.\"), \n null;\n throw e;\n }\n try {\n // BloomFilter throws error if the inputs are invalid.\n o = new BloomFilter(s, r, i);\n } catch (e) {\n return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError ? \"BloomFilter error: \" : \"Applying bloom filter failed: \", e), \n null;\n }\n return 0 === o.Ie ? null : o;\n }\n /**\n * Apply bloom filter to remove the deleted documents, and return the\n * application status.\n */ Xe(e, t, n) {\n return t.me.count === n - this.nt(e, t.targetId) ? 0 /* BloomFilterApplicationStatus.Success */ : 2 /* BloomFilterApplicationStatus.FalsePositive */;\n }\n /**\n * Filter out removed documents based on bloom filter membership result and\n * return number of documents removed.\n */ nt(e, t) {\n const n = this.Le.getRemoteKeysForTarget(t);\n let r = 0;\n return n.forEach((n => {\n const i = this.Le.tt(), s = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;\n e.mightContain(s) || (this.Ue(t, n, /*updatedDocument=*/ null), r++);\n })), r;\n }\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */ rt(e) {\n const t = new Map;\n this.Be.forEach(((n, r) => {\n const i = this.Je(r);\n if (i) {\n if (n.current && __PRIVATE_targetIsDocumentTarget(i.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const t = new DocumentKey(i.target.path);\n null !== this.ke.get(t) || this.it(r, t) || this.Ue(r, t, MutableDocument.newNoDocument(t, e));\n }\n n.be && (t.set(r, n.ve()), n.Ce());\n }\n }));\n let n = __PRIVATE_documentKeySet();\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n \n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.qe.forEach(((e, t) => {\n let r = !0;\n t.forEachWhile((e => {\n const t = this.Je(e);\n return !t || \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ === t.purpose || (r = !1, \n !1);\n })), r && (n = n.add(e));\n })), this.ke.forEach(((t, n) => n.setReadTime(e)));\n const r = new RemoteEvent(e, t, this.Qe, this.ke, n);\n return this.ke = __PRIVATE_mutableDocumentMap(), this.qe = __PRIVATE_documentTargetMap(), \n this.Qe = new SortedMap(__PRIVATE_primitiveComparator), r;\n }\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n $e(e, t) {\n if (!this.ze(e)) return;\n const n = this.it(e, t.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;\n this.Ge(e).Fe(t.key, n), this.ke = this.ke.insert(t.key, t), this.qe = this.qe.insert(t.key, this.st(t.key).add(e));\n }\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n Ue(e, t, n) {\n if (!this.ze(e)) return;\n const r = this.Ge(e);\n this.it(e, t) ? r.Fe(t, 1 /* ChangeType.Removed */) : \n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n r.Me(t), this.qe = this.qe.insert(t, this.st(t).delete(e)), n && (this.ke = this.ke.insert(t, n));\n }\n removeTarget(e) {\n this.Be.delete(e);\n }\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */ Ye(e) {\n const t = this.Ge(e).ve();\n return this.Le.getRemoteKeysForTarget(e).size + t.addedDocuments.size - t.removedDocuments.size;\n }\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */ xe(e) {\n this.Ge(e).xe();\n }\n Ge(e) {\n let t = this.Be.get(e);\n return t || (t = new __PRIVATE_TargetState, this.Be.set(e, t)), t;\n }\n st(e) {\n let t = this.qe.get(e);\n return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.qe = this.qe.insert(e, t)), \n t;\n }\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */ ze(e) {\n const t = null !== this.Je(e);\n return t || __PRIVATE_logDebug(\"WatchChangeAggregator\", \"Detected inactive target\", e), \n t;\n }\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */ Je(e) {\n const t = this.Be.get(e);\n return t && t.Se ? null : this.Le.ot(e);\n }\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */ je(e) {\n this.Be.set(e, new __PRIVATE_TargetState);\n this.Le.getRemoteKeysForTarget(e).forEach((t => {\n this.Ue(e, t, /*updatedDocument=*/ null);\n }));\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */ it(e, t) {\n return this.Le.getRemoteKeysForTarget(e).has(t);\n }\n}\n\nfunction __PRIVATE_documentTargetMap() {\n return new SortedMap(DocumentKey.comparator);\n}\n\nfunction __PRIVATE_snapshotChangesMap() {\n return new SortedMap(DocumentKey.comparator);\n}\n\nconst Te = (() => {\n const e = {\n asc: \"ASCENDING\",\n desc: \"DESCENDING\"\n };\n return e;\n})(), Ee = (() => {\n const e = {\n \"<\": \"LESS_THAN\",\n \"<=\": \"LESS_THAN_OR_EQUAL\",\n \">\": \"GREATER_THAN\",\n \">=\": \"GREATER_THAN_OR_EQUAL\",\n \"==\": \"EQUAL\",\n \"!=\": \"NOT_EQUAL\",\n \"array-contains\": \"ARRAY_CONTAINS\",\n in: \"IN\",\n \"not-in\": \"NOT_IN\",\n \"array-contains-any\": \"ARRAY_CONTAINS_ANY\"\n };\n return e;\n})(), de = (() => {\n const e = {\n and: \"AND\",\n or: \"OR\"\n };\n return e;\n})();\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nclass JsonProtoSerializer {\n constructor(e, t) {\n this.databaseId = e, this.useProto3Json = t;\n }\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction __PRIVATE_toInt32Proto(e, t) {\n return e.useProto3Json || __PRIVATE_isNullOrUndefined(t) ? t : {\n value: t\n };\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nfunction toTimestamp(e, t) {\n if (e.useProto3Json) {\n return `${new Date(1e3 * t.seconds).toISOString().replace(/\\.\\d*/, \"\").replace(\"Z\", \"\")}.${(\"000000000\" + t.nanoseconds).slice(-9)}Z`;\n }\n return {\n seconds: \"\" + t.seconds,\n nanos: t.nanoseconds\n };\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nfunction __PRIVATE_toBytes(e, t) {\n return e.useProto3Json ? t.toBase64() : t.toUint8Array();\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */ function __PRIVATE_toVersion(e, t) {\n return toTimestamp(e, t.toTimestamp());\n}\n\nfunction __PRIVATE_fromVersion(e) {\n return __PRIVATE_hardAssert(!!e), SnapshotVersion.fromTimestamp(function fromTimestamp(e) {\n const t = __PRIVATE_normalizeTimestamp(e);\n return new Timestamp(t.seconds, t.nanos);\n }(e));\n}\n\nfunction __PRIVATE_toResourceName(e, t) {\n return __PRIVATE_toResourcePath(e, t).canonicalString();\n}\n\nfunction __PRIVATE_toResourcePath(e, t) {\n const n = function __PRIVATE_fullyQualifiedPrefixPath(e) {\n return new ResourcePath([ \"projects\", e.projectId, \"databases\", e.database ]);\n }(e).child(\"documents\");\n return void 0 === t ? n : n.child(t);\n}\n\nfunction __PRIVATE_fromResourceName(e) {\n const t = ResourcePath.fromString(e);\n return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t)), t;\n}\n\nfunction __PRIVATE_toName(e, t) {\n return __PRIVATE_toResourceName(e.databaseId, t.path);\n}\n\nfunction fromName(e, t) {\n const n = __PRIVATE_fromResourceName(t);\n if (n.get(1) !== e.databaseId.projectId) throw new FirestoreError(D.INVALID_ARGUMENT, \"Tried to deserialize key from different project: \" + n.get(1) + \" vs \" + e.databaseId.projectId);\n if (n.get(3) !== e.databaseId.database) throw new FirestoreError(D.INVALID_ARGUMENT, \"Tried to deserialize key from different database: \" + n.get(3) + \" vs \" + e.databaseId.database);\n return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n));\n}\n\nfunction __PRIVATE_toQueryPath(e, t) {\n return __PRIVATE_toResourceName(e.databaseId, t);\n}\n\nfunction __PRIVATE_fromQueryPath(e) {\n const t = __PRIVATE_fromResourceName(e);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n return 4 === t.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t);\n}\n\nfunction __PRIVATE_getEncodedDatabaseId(e) {\n return new ResourcePath([ \"projects\", e.databaseId.projectId, \"databases\", e.databaseId.database ]).canonicalString();\n}\n\nfunction __PRIVATE_extractLocalPathFromResourceName(e) {\n return __PRIVATE_hardAssert(e.length > 4 && \"documents\" === e.get(4)), e.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */ function __PRIVATE_toMutationDocument(e, t, n) {\n return {\n name: __PRIVATE_toName(e, t),\n fields: n.value.mapValue.fields\n };\n}\n\nfunction __PRIVATE_fromDocument(e, t, n) {\n const r = fromName(e, t.name), i = __PRIVATE_fromVersion(t.updateTime), s = t.createTime ? __PRIVATE_fromVersion(t.createTime) : SnapshotVersion.min(), o = new ObjectValue({\n mapValue: {\n fields: t.fields\n }\n }), _ = MutableDocument.newFoundDocument(r, i, s, o);\n return n && _.setHasCommittedMutations(), n ? _.setHasCommittedMutations() : _;\n}\n\nfunction __PRIVATE_fromBatchGetDocumentsResponse(e, t) {\n return \"found\" in t ? function __PRIVATE_fromFound(e, t) {\n __PRIVATE_hardAssert(!!t.found), t.found.name, t.found.updateTime;\n const n = fromName(e, t.found.name), r = __PRIVATE_fromVersion(t.found.updateTime), i = t.found.createTime ? __PRIVATE_fromVersion(t.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({\n mapValue: {\n fields: t.found.fields\n }\n });\n return MutableDocument.newFoundDocument(n, r, i, s);\n }(e, t) : \"missing\" in t ? function __PRIVATE_fromMissing(e, t) {\n __PRIVATE_hardAssert(!!t.missing), __PRIVATE_hardAssert(!!t.readTime);\n const n = fromName(e, t.missing), r = __PRIVATE_fromVersion(t.readTime);\n return MutableDocument.newNoDocument(n, r);\n }(e, t) : fail();\n}\n\nfunction __PRIVATE_fromWatchChange(e, t) {\n let n;\n if (\"targetChange\" in t) {\n t.targetChange;\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const r = function __PRIVATE_fromWatchTargetChangeState(e) {\n return \"NO_CHANGE\" === e ? 0 /* WatchTargetChangeState.NoChange */ : \"ADD\" === e ? 1 /* WatchTargetChangeState.Added */ : \"REMOVE\" === e ? 2 /* WatchTargetChangeState.Removed */ : \"CURRENT\" === e ? 3 /* WatchTargetChangeState.Current */ : \"RESET\" === e ? 4 /* WatchTargetChangeState.Reset */ : fail();\n }(t.targetChange.targetChangeType || \"NO_CHANGE\"), i = t.targetChange.targetIds || [], s = function __PRIVATE_fromBytes(e, t) {\n return e.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t || \"string\" == typeof t), \n ByteString.fromBase64String(t || \"\")) : (__PRIVATE_hardAssert(void 0 === t || \n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n t instanceof Buffer || t instanceof Uint8Array), ByteString.fromUint8Array(t || new Uint8Array));\n }(e, t.targetChange.resumeToken), o = t.targetChange.cause, _ = o && function __PRIVATE_fromRpcStatus(e) {\n const t = void 0 === e.code ? D.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e.code);\n return new FirestoreError(t, e.message || \"\");\n }(o);\n n = new __PRIVATE_WatchTargetChange(r, i, s, _ || null);\n } else if (\"documentChange\" in t) {\n t.documentChange;\n const r = t.documentChange;\n r.document, r.document.name, r.document.updateTime;\n const i = fromName(e, r.document.name), s = __PRIVATE_fromVersion(r.document.updateTime), o = r.document.createTime ? __PRIVATE_fromVersion(r.document.createTime) : SnapshotVersion.min(), _ = new ObjectValue({\n mapValue: {\n fields: r.document.fields\n }\n }), a = MutableDocument.newFoundDocument(i, s, o, _), u = r.targetIds || [], c = r.removedTargetIds || [];\n n = new __PRIVATE_DocumentWatchChange(u, c, a.key, a);\n } else if (\"documentDelete\" in t) {\n t.documentDelete;\n const r = t.documentDelete;\n r.document;\n const i = fromName(e, r.document), s = r.readTime ? __PRIVATE_fromVersion(r.readTime) : SnapshotVersion.min(), o = MutableDocument.newNoDocument(i, s), _ = r.removedTargetIds || [];\n n = new __PRIVATE_DocumentWatchChange([], _, o.key, o);\n } else if (\"documentRemove\" in t) {\n t.documentRemove;\n const r = t.documentRemove;\n r.document;\n const i = fromName(e, r.document), s = r.removedTargetIds || [];\n n = new __PRIVATE_DocumentWatchChange([], s, i, null);\n } else {\n if (!(\"filter\" in t)) return fail();\n {\n t.filter;\n const e = t.filter;\n e.targetId;\n const {count: r = 0, unchangedNames: i} = e, s = new ExistenceFilter(r, i), o = e.targetId;\n n = new __PRIVATE_ExistenceFilterChange(o, s);\n }\n }\n return n;\n}\n\nfunction toMutation(e, t) {\n let n;\n if (t instanceof __PRIVATE_SetMutation) n = {\n update: __PRIVATE_toMutationDocument(e, t.key, t.value)\n }; else if (t instanceof __PRIVATE_DeleteMutation) n = {\n delete: __PRIVATE_toName(e, t.key)\n }; else if (t instanceof __PRIVATE_PatchMutation) n = {\n update: __PRIVATE_toMutationDocument(e, t.key, t.data),\n updateMask: __PRIVATE_toDocumentMask(t.fieldMask)\n }; else {\n if (!(t instanceof __PRIVATE_VerifyMutation)) return fail();\n n = {\n verify: __PRIVATE_toName(e, t.key)\n };\n }\n return t.fieldTransforms.length > 0 && (n.updateTransforms = t.fieldTransforms.map((e => function __PRIVATE_toFieldTransform(e, t) {\n const n = t.transform;\n if (n instanceof __PRIVATE_ServerTimestampTransform) return {\n fieldPath: t.field.canonicalString(),\n setToServerValue: \"REQUEST_TIME\"\n };\n if (n instanceof __PRIVATE_ArrayUnionTransformOperation) return {\n fieldPath: t.field.canonicalString(),\n appendMissingElements: {\n values: n.elements\n }\n };\n if (n instanceof __PRIVATE_ArrayRemoveTransformOperation) return {\n fieldPath: t.field.canonicalString(),\n removeAllFromArray: {\n values: n.elements\n }\n };\n if (n instanceof __PRIVATE_NumericIncrementTransformOperation) return {\n fieldPath: t.field.canonicalString(),\n increment: n.Pe\n };\n throw fail();\n }(0, e)))), t.precondition.isNone || (n.currentDocument = function __PRIVATE_toPrecondition(e, t) {\n return void 0 !== t.updateTime ? {\n updateTime: __PRIVATE_toVersion(e, t.updateTime)\n } : void 0 !== t.exists ? {\n exists: t.exists\n } : fail();\n }(e, t.precondition)), n;\n}\n\nfunction __PRIVATE_fromMutation(e, t) {\n const n = t.currentDocument ? function __PRIVATE_fromPrecondition(e) {\n return void 0 !== e.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)) : void 0 !== e.exists ? Precondition.exists(e.exists) : Precondition.none();\n }(t.currentDocument) : Precondition.none(), r = t.updateTransforms ? t.updateTransforms.map((t => function __PRIVATE_fromFieldTransform(e, t) {\n let n = null;\n if (\"setToServerValue\" in t) __PRIVATE_hardAssert(\"REQUEST_TIME\" === t.setToServerValue), \n n = new __PRIVATE_ServerTimestampTransform; else if (\"appendMissingElements\" in t) {\n const e = t.appendMissingElements.values || [];\n n = new __PRIVATE_ArrayUnionTransformOperation(e);\n } else if (\"removeAllFromArray\" in t) {\n const e = t.removeAllFromArray.values || [];\n n = new __PRIVATE_ArrayRemoveTransformOperation(e);\n } else \"increment\" in t ? n = new __PRIVATE_NumericIncrementTransformOperation(e, t.increment) : fail();\n const r = FieldPath$1.fromServerFormat(t.fieldPath);\n return new FieldTransform(r, n);\n }(e, t))) : [];\n if (t.update) {\n t.update.name;\n const i = fromName(e, t.update.name), s = new ObjectValue({\n mapValue: {\n fields: t.update.fields\n }\n });\n if (t.updateMask) {\n const e = function __PRIVATE_fromDocumentMask(e) {\n const t = e.fieldPaths || [];\n return new FieldMask(t.map((e => FieldPath$1.fromServerFormat(e))));\n }(t.updateMask);\n return new __PRIVATE_PatchMutation(i, s, e, n, r);\n }\n return new __PRIVATE_SetMutation(i, s, n, r);\n }\n if (t.delete) {\n const r = fromName(e, t.delete);\n return new __PRIVATE_DeleteMutation(r, n);\n }\n if (t.verify) {\n const r = fromName(e, t.verify);\n return new __PRIVATE_VerifyMutation(r, n);\n }\n return fail();\n}\n\nfunction __PRIVATE_fromWriteResults(e, t) {\n return e && e.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t), e.map((e => function __PRIVATE_fromWriteResult(e, t) {\n // NOTE: Deletes don't have an updateTime.\n let n = e.updateTime ? __PRIVATE_fromVersion(e.updateTime) : __PRIVATE_fromVersion(t);\n return n.isEqual(SnapshotVersion.min()) && (\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n n = __PRIVATE_fromVersion(t)), new MutationResult(n, e.transformResults || []);\n }(e, t)))) : [];\n}\n\nfunction __PRIVATE_toDocumentsTarget(e, t) {\n return {\n documents: [ __PRIVATE_toQueryPath(e, t.path) ]\n };\n}\n\nfunction __PRIVATE_toQueryTarget(e, t) {\n // Dissect the path into parent, collectionId, and optional key filter.\n const n = {\n structuredQuery: {}\n }, r = t.path;\n let i;\n null !== t.collectionGroup ? (i = r, n.structuredQuery.from = [ {\n collectionId: t.collectionGroup,\n allDescendants: !0\n } ]) : (i = r.popLast(), n.structuredQuery.from = [ {\n collectionId: r.lastSegment()\n } ]), n.parent = __PRIVATE_toQueryPath(e, i);\n const s = function __PRIVATE_toFilters(e) {\n if (0 === e.length) return;\n return __PRIVATE_toFilter(CompositeFilter.create(e, \"and\" /* CompositeOperator.AND */));\n }(t.filters);\n s && (n.structuredQuery.where = s);\n const o = function __PRIVATE_toOrder(e) {\n if (0 === e.length) return;\n return e.map((e => \n // visible for testing\n function __PRIVATE_toPropertyOrder(e) {\n return {\n field: __PRIVATE_toFieldPathReference(e.field),\n direction: __PRIVATE_toDirection(e.dir)\n };\n }(e)));\n }(t.orderBy);\n o && (n.structuredQuery.orderBy = o);\n const _ = __PRIVATE_toInt32Proto(e, t.limit);\n return null !== _ && (n.structuredQuery.limit = _), t.startAt && (n.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(e) {\n return {\n before: e.inclusive,\n values: e.position\n };\n }(t.startAt)), t.endAt && (n.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(e) {\n return {\n before: !e.inclusive,\n values: e.position\n };\n }(t.endAt)), {\n _t: n,\n parent: i\n };\n}\n\nfunction __PRIVATE_toRunAggregationQueryRequest(e, t, n, r) {\n const {_t: i, parent: s} = __PRIVATE_toQueryTarget(e, t), o = {}, _ = [];\n let a = 0;\n return n.forEach((e => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const t = r ? e.alias : \"aggregate_\" + a++;\n o[t] = e.alias, \"count\" === e.aggregateType ? _.push({\n alias: t,\n count: {}\n }) : \"avg\" === e.aggregateType ? _.push({\n alias: t,\n avg: {\n field: __PRIVATE_toFieldPathReference(e.fieldPath)\n }\n }) : \"sum\" === e.aggregateType && _.push({\n alias: t,\n sum: {\n field: __PRIVATE_toFieldPathReference(e.fieldPath)\n }\n });\n })), {\n request: {\n structuredAggregationQuery: {\n aggregations: _,\n structuredQuery: i.structuredQuery\n },\n parent: i.parent\n },\n ut: o,\n parent: s\n };\n}\n\nfunction __PRIVATE_convertQueryTargetToQuery(e) {\n let t = __PRIVATE_fromQueryPath(e.parent);\n const n = e.structuredQuery, r = n.from ? n.from.length : 0;\n let i = null;\n if (r > 0) {\n __PRIVATE_hardAssert(1 === r);\n const e = n.from[0];\n e.allDescendants ? i = e.collectionId : t = t.child(e.collectionId);\n }\n let s = [];\n n.where && (s = function __PRIVATE_fromFilters(e) {\n const t = __PRIVATE_fromFilter(e);\n if (t instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t)) return t.getFilters();\n return [ t ];\n }(n.where));\n let o = [];\n n.orderBy && (o = function __PRIVATE_fromOrder(e) {\n return e.map((e => function __PRIVATE_fromPropertyOrder(e) {\n return new OrderBy(__PRIVATE_fromFieldPathReference(e.field), \n // visible for testing\n function __PRIVATE_fromDirection(e) {\n switch (e) {\n case \"ASCENDING\":\n return \"asc\" /* Direction.ASCENDING */;\n\n case \"DESCENDING\":\n return \"desc\" /* Direction.DESCENDING */;\n\n default:\n return;\n }\n }\n // visible for testing\n (e.direction));\n }\n // visible for testing\n (e)));\n }(n.orderBy));\n let _ = null;\n n.limit && (_ = function __PRIVATE_fromInt32Proto(e) {\n let t;\n return t = \"object\" == typeof e ? e.value : e, __PRIVATE_isNullOrUndefined(t) ? null : t;\n }(n.limit));\n let a = null;\n n.startAt && (a = function __PRIVATE_fromStartAtCursor(e) {\n const t = !!e.before, n = e.values || [];\n return new Bound(n, t);\n }(n.startAt));\n let u = null;\n return n.endAt && (u = function __PRIVATE_fromEndAtCursor(e) {\n const t = !e.before, n = e.values || [];\n return new Bound(n, t);\n }\n // visible for testing\n (n.endAt)), __PRIVATE_newQuery(t, i, o, s, _, \"F\" /* LimitType.First */ , a, u);\n}\n\nfunction __PRIVATE_toListenRequestLabels(e, t) {\n const n = function __PRIVATE_toLabel(e) {\n switch (e) {\n case \"TargetPurposeListen\" /* TargetPurpose.Listen */ :\n return null;\n\n case \"TargetPurposeExistenceFilterMismatch\" /* TargetPurpose.ExistenceFilterMismatch */ :\n return \"existence-filter-mismatch\";\n\n case \"TargetPurposeExistenceFilterMismatchBloom\" /* TargetPurpose.ExistenceFilterMismatchBloom */ :\n return \"existence-filter-mismatch-bloom\";\n\n case \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ :\n return \"limbo-document\";\n\n default:\n return fail();\n }\n }(t.purpose);\n return null == n ? null : {\n \"goog-listen-tags\": n\n };\n}\n\nfunction __PRIVATE_fromFilter(e) {\n return void 0 !== e.unaryFilter ? function __PRIVATE_fromUnaryFilter(e) {\n switch (e.unaryFilter.op) {\n case \"IS_NAN\":\n const t = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n return FieldFilter.create(t, \"==\" /* Operator.EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NULL\":\n const n = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n return FieldFilter.create(n, \"==\" /* Operator.EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n case \"IS_NOT_NAN\":\n const r = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n return FieldFilter.create(r, \"!=\" /* Operator.NOT_EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NOT_NULL\":\n const i = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n return FieldFilter.create(i, \"!=\" /* Operator.NOT_EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n default:\n return fail();\n }\n }(e) : void 0 !== e.fieldFilter ? function __PRIVATE_fromFieldFilter(e) {\n return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field), function __PRIVATE_fromOperatorName(e) {\n switch (e) {\n case \"EQUAL\":\n return \"==\" /* Operator.EQUAL */;\n\n case \"NOT_EQUAL\":\n return \"!=\" /* Operator.NOT_EQUAL */;\n\n case \"GREATER_THAN\":\n return \">\" /* Operator.GREATER_THAN */;\n\n case \"GREATER_THAN_OR_EQUAL\":\n return \">=\" /* Operator.GREATER_THAN_OR_EQUAL */;\n\n case \"LESS_THAN\":\n return \"<\" /* Operator.LESS_THAN */;\n\n case \"LESS_THAN_OR_EQUAL\":\n return \"<=\" /* Operator.LESS_THAN_OR_EQUAL */;\n\n case \"ARRAY_CONTAINS\":\n return \"array-contains\" /* Operator.ARRAY_CONTAINS */;\n\n case \"IN\":\n return \"in\" /* Operator.IN */;\n\n case \"NOT_IN\":\n return \"not-in\" /* Operator.NOT_IN */;\n\n case \"ARRAY_CONTAINS_ANY\":\n return \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */;\n\n default:\n return fail();\n }\n }(e.fieldFilter.op), e.fieldFilter.value);\n }(e) : void 0 !== e.compositeFilter ? function __PRIVATE_fromCompositeFilter(e) {\n return CompositeFilter.create(e.compositeFilter.filters.map((e => __PRIVATE_fromFilter(e))), function __PRIVATE_fromCompositeOperatorName(e) {\n switch (e) {\n case \"AND\":\n return \"and\" /* CompositeOperator.AND */;\n\n case \"OR\":\n return \"or\" /* CompositeOperator.OR */;\n\n default:\n return fail();\n }\n }(e.compositeFilter.op));\n }(e) : fail();\n}\n\nfunction __PRIVATE_toDirection(e) {\n return Te[e];\n}\n\nfunction __PRIVATE_toOperatorName(e) {\n return Ee[e];\n}\n\nfunction __PRIVATE_toCompositeOperatorName(e) {\n return de[e];\n}\n\nfunction __PRIVATE_toFieldPathReference(e) {\n return {\n fieldPath: e.canonicalString()\n };\n}\n\nfunction __PRIVATE_fromFieldPathReference(e) {\n return FieldPath$1.fromServerFormat(e.fieldPath);\n}\n\nfunction __PRIVATE_toFilter(e) {\n return e instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(e) {\n if (\"==\" /* Operator.EQUAL */ === e.op) {\n if (__PRIVATE_isNanValue(e.value)) return {\n unaryFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: \"IS_NAN\"\n }\n };\n if (__PRIVATE_isNullValue(e.value)) return {\n unaryFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: \"IS_NULL\"\n }\n };\n } else if (\"!=\" /* Operator.NOT_EQUAL */ === e.op) {\n if (__PRIVATE_isNanValue(e.value)) return {\n unaryFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: \"IS_NOT_NAN\"\n }\n };\n if (__PRIVATE_isNullValue(e.value)) return {\n unaryFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: \"IS_NOT_NULL\"\n }\n };\n }\n return {\n fieldFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: __PRIVATE_toOperatorName(e.op),\n value: e.value\n }\n };\n }(e) : e instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(e) {\n const t = e.getFilters().map((e => __PRIVATE_toFilter(e)));\n if (1 === t.length) return t[0];\n return {\n compositeFilter: {\n op: __PRIVATE_toCompositeOperatorName(e.op),\n filters: t\n }\n };\n }(e) : fail();\n}\n\nfunction __PRIVATE_toDocumentMask(e) {\n const t = [];\n return e.fields.forEach((e => t.push(e.canonicalString()))), {\n fieldPaths: t\n };\n}\n\nfunction __PRIVATE_isValidResourceName(e) {\n // Resource names have at least 4 components (project ID, database ID)\n return e.length >= 4 && \"projects\" === e.get(0) && \"databases\" === e.get(2);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */ class TargetData {\n constructor(\n /** The target being listened to. */\n e, \n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n t, \n /** The purpose of the target. */\n n, \n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n r, \n /** The latest snapshot version seen for this target. */\n i = SnapshotVersion.min()\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */ , s = SnapshotVersion.min()\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */ , o = ByteString.EMPTY_BYTE_STRING\n /**\n * The number of documents that last matched the query at the resume token or\n * read time. Documents are counted only when making a listen request with\n * resume token or read time, otherwise, keep it null.\n */ , _ = null) {\n this.target = e, this.targetId = t, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i, \n this.lastLimboFreeSnapshotVersion = s, this.resumeToken = o, this.expectedCount = _;\n }\n /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(e) {\n return new TargetData(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);\n }\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */ withResumeToken(e, t) {\n return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, t, this.lastLimboFreeSnapshotVersion, e, \n /* expectedCount= */ null);\n }\n /**\n * Creates a new target data instance with an updated expected count.\n */ withExpectedCount(e) {\n return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e);\n }\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */ withLastLimboFreeSnapshotVersion(e) {\n return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Serializer for values stored in the LocalStore. */ class __PRIVATE_LocalSerializer {\n constructor(e) {\n this.ct = e;\n }\n}\n\n/** Decodes a remote document from storage locally to a Document. */ function __PRIVATE_fromDbRemoteDocument(e, t) {\n let n;\n if (t.document) n = __PRIVATE_fromDocument(e.ct, t.document, !!t.hasCommittedMutations); else if (t.noDocument) {\n const e = DocumentKey.fromSegments(t.noDocument.path), r = __PRIVATE_fromDbTimestamp(t.noDocument.readTime);\n n = MutableDocument.newNoDocument(e, r), t.hasCommittedMutations && n.setHasCommittedMutations();\n } else {\n if (!t.unknownDocument) return fail();\n {\n const e = DocumentKey.fromSegments(t.unknownDocument.path), r = __PRIVATE_fromDbTimestamp(t.unknownDocument.version);\n n = MutableDocument.newUnknownDocument(e, r);\n }\n }\n return t.readTime && n.setReadTime(function __PRIVATE_fromDbTimestampKey(e) {\n const t = new Timestamp(e[0], e[1]);\n return SnapshotVersion.fromTimestamp(t);\n }(t.readTime)), n;\n}\n\n/** Encodes a document for storage locally. */ function __PRIVATE_toDbRemoteDocument(e, t) {\n const n = t.key, r = {\n prefixPath: n.getCollectionPath().popLast().toArray(),\n collectionGroup: n.collectionGroup,\n documentId: n.path.lastSegment(),\n readTime: __PRIVATE_toDbTimestampKey(t.readTime),\n hasCommittedMutations: t.hasCommittedMutations\n };\n if (t.isFoundDocument()) r.document = function __PRIVATE_toDocument(e, t) {\n return {\n name: __PRIVATE_toName(e, t.key),\n fields: t.data.value.mapValue.fields,\n updateTime: toTimestamp(e, t.version.toTimestamp()),\n createTime: toTimestamp(e, t.createTime.toTimestamp())\n };\n }(e.ct, t); else if (t.isNoDocument()) r.noDocument = {\n path: n.path.toArray(),\n readTime: __PRIVATE_toDbTimestamp(t.version)\n }; else {\n if (!t.isUnknownDocument()) return fail();\n r.unknownDocument = {\n path: n.path.toArray(),\n version: __PRIVATE_toDbTimestamp(t.version)\n };\n }\n return r;\n}\n\nfunction __PRIVATE_toDbTimestampKey(e) {\n const t = e.toTimestamp();\n return [ t.seconds, t.nanoseconds ];\n}\n\nfunction __PRIVATE_toDbTimestamp(e) {\n const t = e.toTimestamp();\n return {\n seconds: t.seconds,\n nanoseconds: t.nanoseconds\n };\n}\n\nfunction __PRIVATE_fromDbTimestamp(e) {\n const t = new Timestamp(e.seconds, e.nanoseconds);\n return SnapshotVersion.fromTimestamp(t);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n/** Decodes a DbMutationBatch into a MutationBatch */\nfunction __PRIVATE_fromDbMutationBatch(e, t) {\n const n = (t.baseMutations || []).map((t => __PRIVATE_fromMutation(e.ct, t)));\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let e = 0; e < t.mutations.length - 1; ++e) {\n const n = t.mutations[e];\n if (e + 1 < t.mutations.length && void 0 !== t.mutations[e + 1].transform) {\n const r = t.mutations[e + 1];\n n.updateTransforms = r.transform.fieldTransforms, t.mutations.splice(e + 1, 1), \n ++e;\n }\n }\n const r = t.mutations.map((t => __PRIVATE_fromMutation(e.ct, t))), i = Timestamp.fromMillis(t.localWriteTimeMs);\n return new MutationBatch(t.batchId, i, n, r);\n}\n\n/** Decodes a DbTarget into TargetData */ function __PRIVATE_fromDbTarget(e) {\n const t = __PRIVATE_fromDbTimestamp(e.readTime), n = void 0 !== e.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion) : SnapshotVersion.min();\n let r;\n return r = \n /**\n * A helper function for figuring out what kind of query has been stored.\n */\n function __PRIVATE_isDocumentQuery(e) {\n return void 0 !== e.documents;\n }\n /** Encodes a DbBundle to a BundleMetadata object. */ (e.query) ? function __PRIVATE_fromDocumentsTarget(e) {\n return __PRIVATE_hardAssert(1 === e.documents.length), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0])));\n }(e.query) : function __PRIVATE_fromQueryTarget(e) {\n return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e));\n }(e.query), new TargetData(r, e.targetId, \"TargetPurposeListen\" /* TargetPurpose.Listen */ , e.lastListenSequenceNumber, t, n, ByteString.fromBase64String(e.resumeToken));\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */ function __PRIVATE_toDbTarget(e, t) {\n const n = __PRIVATE_toDbTimestamp(t.snapshotVersion), r = __PRIVATE_toDbTimestamp(t.lastLimboFreeSnapshotVersion);\n let i;\n i = __PRIVATE_targetIsDocumentTarget(t.target) ? __PRIVATE_toDocumentsTarget(e.ct, t.target) : __PRIVATE_toQueryTarget(e.ct, t.target)._t;\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const s = t.resumeToken.toBase64();\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: t.targetId,\n canonicalId: __PRIVATE_canonifyTarget(t.target),\n readTime: n,\n resumeToken: s,\n lastListenSequenceNumber: t.sequenceNumber,\n lastLimboFreeSnapshotVersion: r,\n query: i\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nfunction __PRIVATE_fromBundledQuery(e) {\n const t = __PRIVATE_convertQueryTargetToQuery({\n parent: e.parent,\n structuredQuery: e.structuredQuery\n });\n return \"LAST\" === e.limitType ? __PRIVATE_queryWithLimit(t, t.limit, \"L\" /* LimitType.Last */) : t;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nfunction __PRIVATE_fromDbDocumentOverlay(e, t) {\n return new Overlay(t.largestBatchId, __PRIVATE_fromMutation(e.ct, t.overlayMutation));\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nfunction __PRIVATE_toDbDocumentOverlayKey(e, t) {\n const n = t.path.lastSegment();\n return [ e, __PRIVATE_encodeResourcePath(t.path.popLast()), n ];\n}\n\nfunction __PRIVATE_toDbIndexState(e, t, n, r) {\n return {\n indexId: e,\n uid: t,\n sequenceNumber: n,\n readTime: __PRIVATE_toDbTimestamp(r.readTime),\n documentKey: __PRIVATE_encodeResourcePath(r.documentKey.path),\n largestBatchId: r.largestBatchId\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 */ class __PRIVATE_IndexedDbBundleCache {\n getBundleMetadata(e, t) {\n return __PRIVATE_bundlesStore(e).get(t).next((e => {\n if (e) return function __PRIVATE_fromDbBundle(e) {\n return {\n id: e.bundleId,\n createTime: __PRIVATE_fromDbTimestamp(e.createTime),\n version: e.version\n };\n }\n /** Encodes a BundleMetadata to a DbBundle. */ (e);\n }));\n }\n saveBundleMetadata(e, t) {\n return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e) {\n return {\n bundleId: e.id,\n createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)),\n version: e.version\n };\n }\n /** Encodes a DbNamedQuery to a NamedQuery. */ (t));\n }\n getNamedQuery(e, t) {\n return __PRIVATE_namedQueriesStore(e).get(t).next((e => {\n if (e) return function __PRIVATE_fromDbNamedQuery(e) {\n return {\n name: e.name,\n query: __PRIVATE_fromBundledQuery(e.bundledQuery),\n readTime: __PRIVATE_fromDbTimestamp(e.readTime)\n };\n }\n /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ (e);\n }));\n }\n saveNamedQuery(e, t) {\n return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e) {\n return {\n name: e.name,\n readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)),\n bundledQuery: e.bundledQuery\n };\n }(t));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */ function __PRIVATE_bundlesStore(e) {\n return __PRIVATE_getStore(e, \"bundles\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */ function __PRIVATE_namedQueriesStore(e) {\n return __PRIVATE_getStore(e, \"namedQueries\");\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */ class __PRIVATE_IndexedDbDocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(e, t) {\n this.serializer = e, this.userId = t;\n }\n static lt(e, t) {\n const n = t.uid || \"\";\n return new __PRIVATE_IndexedDbDocumentOverlayCache(e, n);\n }\n getOverlay(e, t) {\n return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t)).next((e => e ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e) : null));\n }\n getOverlays(e, t) {\n const n = __PRIVATE_newOverlayMap();\n return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => {\n null !== e && n.set(t, e);\n })))).next((() => n));\n }\n saveOverlays(e, t, n) {\n const r = [];\n return n.forEach(((n, i) => {\n const s = new Overlay(t, i);\n r.push(this.ht(e, s));\n })), PersistencePromise.waitFor(r);\n }\n removeOverlaysForBatchId(e, t, n) {\n const r = new Set;\n // Get the set of unique collection paths.\n t.forEach((e => r.add(__PRIVATE_encodeResourcePath(e.getCollectionPath()))));\n const i = [];\n return r.forEach((t => {\n const r = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, n + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n i.push(__PRIVATE_documentOverlayStore(e).j(\"collectionPathOverlayIndex\", r));\n })), PersistencePromise.waitFor(i);\n }\n getOverlaysForCollection(e, t, n) {\n const r = __PRIVATE_newOverlayMap(), i = __PRIVATE_encodeResourcePath(t), s = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return __PRIVATE_documentOverlayStore(e).U(\"collectionPathOverlayIndex\", s).next((e => {\n for (const t of e) {\n const e = __PRIVATE_fromDbDocumentOverlay(this.serializer, t);\n r.set(e.getKey(), e);\n }\n return r;\n }));\n }\n getOverlaysForCollectionGroup(e, t, n, r) {\n const i = __PRIVATE_newOverlayMap();\n let s;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const o = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return __PRIVATE_documentOverlayStore(e).J({\n index: \"collectionGroupOverlayIndex\",\n range: o\n }, ((e, t, n) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const o = __PRIVATE_fromDbDocumentOverlay(this.serializer, t);\n i.size() < r || o.largestBatchId === s ? (i.set(o.getKey(), o), s = o.largestBatchId) : n.done();\n })).next((() => i));\n }\n ht(e, t) {\n return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e, t, n) {\n const [r, i, s] = __PRIVATE_toDbDocumentOverlayKey(t, n.mutation.key);\n return {\n userId: t,\n collectionPath: i,\n documentId: s,\n collectionGroup: n.mutation.key.getCollectionGroup(),\n largestBatchId: n.largestBatchId,\n overlayMutation: toMutation(e.ct, n.mutation)\n };\n }(this.serializer, this.userId, t));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */ function __PRIVATE_documentOverlayStore(e) {\n return __PRIVATE_getStore(e, \"documentOverlays\");\n}\n\n/**\n * @license\n * Copyright 2024 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 */ class __PRIVATE_IndexedDbGlobalsCache {\n Pt(e) {\n return __PRIVATE_getStore(e, \"globals\");\n }\n getSessionToken(e) {\n return this.Pt(e).get(\"sessionToken\").next((e => {\n const t = null == e ? void 0 : e.value;\n return t ? ByteString.fromUint8Array(t) : ByteString.EMPTY_BYTE_STRING;\n }));\n }\n setSessionToken(e, t) {\n return this.Pt(e).put({\n name: \"sessionToken\",\n value: t.toUint8Array()\n });\n }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n/** Firestore index value writer. */\nclass __PRIVATE_FirestoreIndexValueWriter {\n constructor() {}\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n // As an example, consider the resulting encoding for:\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n /** Writes an index value. */\n It(e, t) {\n this.Tt(e, t), \n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n t.Et();\n }\n Tt(e, t) {\n if (\"nullValue\" in e) this.dt(t, 5); else if (\"booleanValue\" in e) this.dt(t, 10), \n t.At(e.booleanValue ? 1 : 0); else if (\"integerValue\" in e) this.dt(t, 15), t.At(__PRIVATE_normalizeNumber(e.integerValue)); else if (\"doubleValue\" in e) {\n const n = __PRIVATE_normalizeNumber(e.doubleValue);\n isNaN(n) ? this.dt(t, 13) : (this.dt(t, 15), __PRIVATE_isNegativeZero(n) ? \n // -0.0, 0 and 0.0 are all considered the same\n t.At(0) : t.At(n));\n } else if (\"timestampValue\" in e) {\n let n = e.timestampValue;\n this.dt(t, 20), \"string\" == typeof n && (n = __PRIVATE_normalizeTimestamp(n)), t.Rt(`${n.seconds || \"\"}`), \n t.At(n.nanos || 0);\n } else if (\"stringValue\" in e) this.Vt(e.stringValue, t), this.ft(t); else if (\"bytesValue\" in e) this.dt(t, 30), \n t.gt(__PRIVATE_normalizeByteString(e.bytesValue)), this.ft(t); else if (\"referenceValue\" in e) this.yt(e.referenceValue, t); else if (\"geoPointValue\" in e) {\n const n = e.geoPointValue;\n this.dt(t, 45), t.At(n.latitude || 0), t.At(n.longitude || 0);\n } else \"mapValue\" in e ? __PRIVATE_isMaxValue(e) ? this.dt(t, Number.MAX_SAFE_INTEGER) : __PRIVATE_isVectorValue(e) ? this.wt(e.mapValue, t) : (this.St(e.mapValue, t), \n this.ft(t)) : \"arrayValue\" in e ? (this.bt(e.arrayValue, t), this.ft(t)) : fail();\n }\n Vt(e, t) {\n this.dt(t, 25), this.Dt(e, t);\n }\n Dt(e, t) {\n t.Rt(e);\n }\n St(e, t) {\n const n = e.fields || {};\n this.dt(t, 55);\n for (const e of Object.keys(n)) this.Vt(e, t), this.Tt(n[e], t);\n }\n wt(e, t) {\n var n, r;\n const i = e.fields || {};\n this.dt(t, 53);\n // Vectors sort first by length\n const s = \"value\", o = (null === (r = null === (n = i[s].arrayValue) || void 0 === n ? void 0 : n.values) || void 0 === r ? void 0 : r.length) || 0;\n this.dt(t, 15), t.At(__PRIVATE_normalizeNumber(o)), \n // Vectors then sort by position value\n this.Vt(s, t), this.Tt(i[s], t);\n }\n bt(e, t) {\n const n = e.values || [];\n this.dt(t, 50);\n for (const e of n) this.Tt(e, t);\n }\n yt(e, t) {\n this.dt(t, 37);\n DocumentKey.fromName(e).path.forEach((e => {\n this.dt(t, 60), this.Dt(e, t);\n }));\n }\n dt(e, t) {\n e.At(t);\n }\n ft(e) {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n e.At(2);\n }\n}\n\n__PRIVATE_FirestoreIndexValueWriter.vt = new __PRIVATE_FirestoreIndexValueWriter;\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nfunction __PRIVATE_numberOfLeadingZerosInByte(e) {\n if (0 === e) return 8;\n let t = 0;\n return e >> 4 == 0 && (\n // Test if the first four bits are zero.\n t += 4, e <<= 4), e >> 6 == 0 && (\n // Test if the first two (or next two) bits are zero.\n t += 2, e <<= 2), e >> 7 == 0 && (\n // Test if the remaining bit is zero.\n t += 1), t;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction __PRIVATE_unsignedNumLength(e) {\n // This is just the number of bytes for the unsigned representation of the number.\n const t = 64 - function __PRIVATE_numberOfLeadingZeros(e) {\n let t = 0;\n for (let n = 0; n < 8; ++n) {\n const r = __PRIVATE_numberOfLeadingZerosInByte(255 & e[n]);\n if (t += r, 8 !== r) break;\n }\n return t;\n }(e);\n return Math.ceil(t / 8);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */ class __PRIVATE_OrderedCodeWriter {\n constructor() {\n this.buffer = new Uint8Array(1024), this.position = 0;\n }\n Ct(e) {\n const t = e[Symbol.iterator]();\n let n = t.next();\n for (;!n.done; ) this.Ft(n.value), n = t.next();\n this.Mt();\n }\n xt(e) {\n const t = e[Symbol.iterator]();\n let n = t.next();\n for (;!n.done; ) this.Ot(n.value), n = t.next();\n this.Nt();\n }\n /** Writes utf8 bytes into this byte sequence, ascending. */ Lt(e) {\n for (const t of e) {\n const e = t.charCodeAt(0);\n if (e < 128) this.Ft(e); else if (e < 2048) this.Ft(960 | e >>> 6), this.Ft(128 | 63 & e); else if (t < \"\\ud800\" || \"\\udbff\" < t) this.Ft(480 | e >>> 12), \n this.Ft(128 | 63 & e >>> 6), this.Ft(128 | 63 & e); else {\n const e = t.codePointAt(0);\n this.Ft(240 | e >>> 18), this.Ft(128 | 63 & e >>> 12), this.Ft(128 | 63 & e >>> 6), \n this.Ft(128 | 63 & e);\n }\n }\n this.Mt();\n }\n /** Writes utf8 bytes into this byte sequence, descending */ Bt(e) {\n for (const t of e) {\n const e = t.charCodeAt(0);\n if (e < 128) this.Ot(e); else if (e < 2048) this.Ot(960 | e >>> 6), this.Ot(128 | 63 & e); else if (t < \"\\ud800\" || \"\\udbff\" < t) this.Ot(480 | e >>> 12), \n this.Ot(128 | 63 & e >>> 6), this.Ot(128 | 63 & e); else {\n const e = t.codePointAt(0);\n this.Ot(240 | e >>> 18), this.Ot(128 | 63 & e >>> 12), this.Ot(128 | 63 & e >>> 6), \n this.Ot(128 | 63 & e);\n }\n }\n this.Nt();\n }\n kt(e) {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const t = this.qt(e), n = __PRIVATE_unsignedNumLength(t);\n this.Qt(1 + n), this.buffer[this.position++] = 255 & n;\n // Write the length\n for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = 255 & t[e];\n }\n Kt(e) {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const t = this.qt(e), n = __PRIVATE_unsignedNumLength(t);\n this.Qt(1 + n), this.buffer[this.position++] = ~(255 & n);\n // Write the length\n for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = ~(255 & t[e]);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */ $t() {\n this.Ut(255), this.Ut(255);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */ Wt() {\n this.Gt(255), this.Gt(255);\n }\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */ reset() {\n this.position = 0;\n }\n seed(e) {\n this.Qt(e.length), this.buffer.set(e, this.position), this.position += e.length;\n }\n /** Makes a copy of the encoded bytes in this buffer. */ zt() {\n return this.buffer.slice(0, this.position);\n }\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */ qt(e) {\n const t = \n /** Converts a JavaScript number to a byte array (using big endian encoding). */\n function __PRIVATE_doubleToLongBits(e) {\n const t = new DataView(new ArrayBuffer(8));\n return t.setFloat64(0, e, /* littleEndian= */ !1), new Uint8Array(t.buffer);\n }(e), n = 0 != (128 & t[0]);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n // Revert the two complement to get natural ordering\n t[0] ^= n ? 255 : 128;\n for (let e = 1; e < t.length; ++e) t[e] ^= n ? 255 : 0;\n return t;\n }\n /** Writes a single byte ascending to the buffer. */ Ft(e) {\n const t = 255 & e;\n 0 === t ? (this.Ut(0), this.Ut(255)) : 255 === t ? (this.Ut(255), this.Ut(0)) : this.Ut(t);\n }\n /** Writes a single byte descending to the buffer. */ Ot(e) {\n const t = 255 & e;\n 0 === t ? (this.Gt(0), this.Gt(255)) : 255 === t ? (this.Gt(255), this.Gt(0)) : this.Gt(e);\n }\n Mt() {\n this.Ut(0), this.Ut(1);\n }\n Nt() {\n this.Gt(0), this.Gt(1);\n }\n Ut(e) {\n this.Qt(1), this.buffer[this.position++] = e;\n }\n Gt(e) {\n this.Qt(1), this.buffer[this.position++] = ~e;\n }\n Qt(e) {\n const t = e + this.position;\n if (t <= this.buffer.length) return;\n // Try doubling.\n let n = 2 * this.buffer.length;\n // Still not big enough? Just allocate the right size.\n n < t && (n = t);\n // Create the new buffer.\n const r = new Uint8Array(n);\n r.set(this.buffer), // copy old data\n this.buffer = r;\n }\n}\n\nclass __PRIVATE_AscendingIndexByteEncoder {\n constructor(e) {\n this.jt = e;\n }\n gt(e) {\n this.jt.Ct(e);\n }\n Rt(e) {\n this.jt.Lt(e);\n }\n At(e) {\n this.jt.kt(e);\n }\n Et() {\n this.jt.$t();\n }\n}\n\nclass __PRIVATE_DescendingIndexByteEncoder {\n constructor(e) {\n this.jt = e;\n }\n gt(e) {\n this.jt.xt(e);\n }\n Rt(e) {\n this.jt.Bt(e);\n }\n At(e) {\n this.jt.Kt(e);\n }\n Et() {\n this.jt.Wt();\n }\n}\n\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */ class __PRIVATE_IndexByteEncoder {\n constructor() {\n this.jt = new __PRIVATE_OrderedCodeWriter, this.Ht = new __PRIVATE_AscendingIndexByteEncoder(this.jt), \n this.Jt = new __PRIVATE_DescendingIndexByteEncoder(this.jt);\n }\n seed(e) {\n this.jt.seed(e);\n }\n Yt(e) {\n return 0 /* IndexKind.ASCENDING */ === e ? this.Ht : this.Jt;\n }\n zt() {\n return this.jt.zt();\n }\n reset() {\n this.jt.reset();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Represents an index entry saved by the SDK in persisted storage. */ class __PRIVATE_IndexEntry {\n constructor(e, t, n, r) {\n this.indexId = e, this.documentKey = t, this.arrayValue = n, this.directionalValue = r;\n }\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */ Zt() {\n const e = this.directionalValue.length, t = 0 === e || 255 === this.directionalValue[e - 1] ? e + 1 : e, n = new Uint8Array(t);\n return n.set(this.directionalValue, 0), t !== e ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1], \n new __PRIVATE_IndexEntry(this.indexId, this.documentKey, this.arrayValue, n);\n }\n}\n\nfunction __PRIVATE_indexEntryComparator(e, t) {\n let n = e.indexId - t.indexId;\n return 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.arrayValue, t.arrayValue), \n 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.directionalValue, t.directionalValue), \n 0 !== n ? n : DocumentKey.comparator(e.documentKey, t.documentKey)));\n}\n\nfunction __PRIVATE_compareByteArrays(e, t) {\n for (let n = 0; n < e.length && n < t.length; ++n) {\n const r = e[n] - t[n];\n if (0 !== r) return r;\n }\n return e.length - t.length;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */ class __PRIVATE_TargetIndexMatcher {\n constructor(e) {\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n this.Xt = new SortedSet(((e, t) => FieldPath$1.comparator(e.field, t.field))), this.collectionId = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment(), \n this.en = e.orderBy, this.tn = [];\n for (const t of e.filters) {\n const e = t;\n e.isInequality() ? this.Xt = this.Xt.add(e) : this.tn.push(e);\n }\n }\n get nn() {\n return this.Xt.size > 1;\n }\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */ rn(e) {\n if (__PRIVATE_hardAssert(e.collectionGroup === this.collectionId), this.nn) \n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return !1;\n // If there is an array element, find a matching filter.\n const t = __PRIVATE_fieldIndexGetArraySegment(e);\n if (void 0 !== t && !this.sn(t)) return !1;\n const n = __PRIVATE_fieldIndexGetDirectionalSegments(e);\n let r = new Set, i = 0, s = 0;\n // Process all equalities first. Equalities can appear out of order.\n for (;i < n.length && this.sn(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString());\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (i === n.length) return !0;\n if (this.Xt.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const e = this.Xt.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!r.has(e.field.canonicalString())) {\n const t = n[i];\n if (!this.on(e, t) || !this._n(this.en[s++], t)) return !1;\n }\n ++i;\n }\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (;i < n.length; ++i) {\n const e = n[i];\n if (s >= this.en.length || !this._n(this.en[s++], e)) return !1;\n }\n return !0;\n }\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */ an() {\n if (this.nn) return null;\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let e = new SortedSet(FieldPath$1.comparator);\n const t = [];\n for (const n of this.tn) {\n if (n.field.isKeyField()) continue;\n if (\"array-contains\" /* Operator.ARRAY_CONTAINS */ === n.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === n.op) t.push(new IndexSegment(n.field, 2 /* IndexKind.CONTAINS */)); else {\n if (e.has(n.field)) continue;\n e = e.add(n.field), t.push(new IndexSegment(n.field, 0 /* IndexKind.ASCENDING */));\n }\n }\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const n of this.en) \n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n n.field.isKeyField() || e.has(n.field) || (e = e.add(n.field), t.push(new IndexSegment(n.field, \"asc\" /* Direction.ASCENDING */ === n.dir ? 0 /* IndexKind.ASCENDING */ : 1 /* IndexKind.DESCENDING */)));\n return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, t, IndexState.empty());\n }\n sn(e) {\n for (const t of this.tn) if (this.on(t, e)) return !0;\n return !1;\n }\n on(e, t) {\n if (void 0 === e || !e.field.isEqual(t.fieldPath)) return !1;\n const n = \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e.op;\n return 2 /* IndexKind.CONTAINS */ === t.kind === n;\n }\n _n(e, t) {\n return !!e.field.isEqual(t.fieldPath) && (0 /* IndexKind.ASCENDING */ === t.kind && \"asc\" /* Direction.ASCENDING */ === e.dir || 1 /* IndexKind.DESCENDING */ === t.kind && \"desc\" /* Direction.DESCENDING */ === e.dir);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */ function __PRIVATE_computeInExpansion(e) {\n var t, n;\n if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n e instanceof FieldFilter) {\n if (e instanceof __PRIVATE_InFilter) {\n const r = (null === (n = null === (t = e.value.arrayValue) || void 0 === t ? void 0 : t.values) || void 0 === n ? void 0 : n.map((t => FieldFilter.create(e.field, \"==\" /* Operator.EQUAL */ , t)))) || [];\n return CompositeFilter.create(r, \"or\" /* CompositeOperator.OR */);\n }\n // We have reached other kinds of field filters.\n return e;\n }\n // We have a composite filter.\n const r = e.filters.map((e => __PRIVATE_computeInExpansion(e)));\n return CompositeFilter.create(r, e.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

    Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */ function __PRIVATE_getDnfTerms(e) {\n if (0 === e.getFilters().length) return [];\n const t = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e));\n return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t)), __PRIVATE_isSingleFieldFilter(t) || __PRIVATE_isFlatConjunction(t) ? [ t ] : t.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function __PRIVATE_isSingleFieldFilter(e) {\n return e instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */ function __PRIVATE_isFlatConjunction(e) {\n return e instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e);\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

    In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

    For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */ function __PRIVATE_isDisjunctiveNormalForm(e) {\n return __PRIVATE_isSingleFieldFilter(e) || __PRIVATE_isFlatConjunction(e) || \n /**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\n function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e) {\n if (e instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e)) {\n for (const t of e.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t) && !__PRIVATE_isFlatConjunction(t)) return !1;\n return !0;\n }\n return !1;\n }(e);\n}\n\nfunction __PRIVATE_computeDistributedNormalForm(e) {\n if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n e instanceof FieldFilter) return e;\n if (1 === e.filters.length) return __PRIVATE_computeDistributedNormalForm(e.filters[0]);\n // Compute DNF for each of the subfilters first\n const t = e.filters.map((e => __PRIVATE_computeDistributedNormalForm(e)));\n let n = CompositeFilter.create(t, e.op);\n return n = __PRIVATE_applyAssociation(n), __PRIVATE_isDisjunctiveNormalForm(n) ? n : (__PRIVATE_hardAssert(n instanceof CompositeFilter), \n __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n)), __PRIVATE_hardAssert(n.filters.length > 1), \n n.filters.reduce(((e, t) => __PRIVATE_applyDistribution(e, t))));\n}\n\nfunction __PRIVATE_applyDistribution(e, t) {\n let n;\n return __PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n __PRIVATE_hardAssert(t instanceof FieldFilter || t instanceof CompositeFilter), \n // FieldFilter FieldFilter\n n = e instanceof FieldFilter ? t instanceof FieldFilter ? function __PRIVATE_applyDistributionFieldFilters(e, t) {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([ e, t ], \"and\" /* CompositeOperator.AND */);\n }(e, t) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) : t instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t, e) : function __PRIVATE_applyDistributionCompositeFilters(e, t) {\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n // Case 1 is a merge.\n if (__PRIVATE_hardAssert(e.filters.length > 0 && t.filters.length > 0), __PRIVATE_compositeFilterIsConjunction(e) && __PRIVATE_compositeFilterIsConjunction(t)) return __PRIVATE_compositeFilterWithAddedFilters(e, t.getFilters());\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const n = __PRIVATE_compositeFilterIsDisjunction(e) ? e : t, r = __PRIVATE_compositeFilterIsDisjunction(e) ? t : e, i = n.filters.map((e => __PRIVATE_applyDistribution(e, r)));\n return CompositeFilter.create(i, \"or\" /* CompositeOperator.OR */);\n }(e, t), __PRIVATE_applyAssociation(n);\n}\n\nfunction __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (__PRIVATE_compositeFilterIsConjunction(t)) \n // Case 1\n return __PRIVATE_compositeFilterWithAddedFilters(t, e.getFilters());\n {\n // Case 2\n const n = t.filters.map((t => __PRIVATE_applyDistribution(e, t)));\n return CompositeFilter.create(n, \"or\" /* CompositeOperator.OR */);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

      \n *
    • A | (B | C) == (A | B) | C == (A | B | C)\n *
    • A & (B & C) == (A & B) & C == (A & B & C)\n *
    \n *\n *

    For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */ function __PRIVATE_applyAssociation(e) {\n if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n e instanceof FieldFilter) return e;\n const t = e.getFilters();\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (1 === t.length) return __PRIVATE_applyAssociation(t[0]);\n // Associativity applied to a flat composite filter results is itself.\n if (__PRIVATE_compositeFilterIsFlat(e)) return e;\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const n = t.map((e => __PRIVATE_applyAssociation(e))), r = [];\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n return n.forEach((t => {\n t instanceof FieldFilter ? r.push(t) : t instanceof CompositeFilter && (t.op === e.op ? \n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n r.push(...t.filters) : \n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n r.push(t));\n })), 1 === r.length ? r[0] : CompositeFilter.create(r, e.op);\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of IndexManager.\n */ class __PRIVATE_MemoryIndexManager {\n constructor() {\n this.un = new __PRIVATE_MemoryCollectionParentIndex;\n }\n addToCollectionParentIndex(e, t) {\n return this.un.add(t), PersistencePromise.resolve();\n }\n getCollectionParents(e, t) {\n return PersistencePromise.resolve(this.un.getEntries(t));\n }\n addFieldIndex(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n deleteFieldIndex(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n deleteAllFieldIndexes(e) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n createTargetIndexes(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n getDocumentsMatchingTarget(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n getIndexType(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(0 /* IndexType.NONE */);\n }\n getFieldIndexes(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve([]);\n }\n getNextCollectionGroupToUpdate(e) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n getMinOffset(e, t) {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n getMinOffsetFromCollectionGroup(e, t) {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n updateCollectionGroup(e, t, n) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n updateIndexEntries(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */ class __PRIVATE_MemoryCollectionParentIndex {\n constructor() {\n this.index = {};\n }\n // Returns false if the entry already existed.\n add(e) {\n const t = e.lastSegment(), n = e.popLast(), r = this.index[t] || new SortedSet(ResourcePath.comparator), i = !r.has(n);\n return this.index[t] = r.add(n), i;\n }\n has(e) {\n const t = e.lastSegment(), n = e.popLast(), r = this.index[t];\n return r && r.has(n);\n }\n getEntries(e) {\n return (this.index[e] || new SortedSet(ResourcePath.comparator)).toArray();\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ae = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nclass __PRIVATE_IndexedDbIndexManager {\n constructor(e, t) {\n this.databaseId = t, \n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n this.cn = new __PRIVATE_MemoryCollectionParentIndex, \n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n this.ln = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), ((e, t) => __PRIVATE_targetEquals(e, t))), \n this.uid = e.uid || \"\";\n }\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */ addToCollectionParentIndex(e, t) {\n if (!this.cn.has(t)) {\n const n = t.lastSegment(), r = t.popLast();\n e.addOnCommittedListener((() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.cn.add(t);\n }));\n const i = {\n collectionId: n,\n parent: __PRIVATE_encodeResourcePath(r)\n };\n return __PRIVATE_collectionParentsStore(e).put(i);\n }\n return PersistencePromise.resolve();\n }\n getCollectionParents(e, t) {\n const n = [], r = IDBKeyRange.bound([ t, \"\" ], [ __PRIVATE_immediateSuccessor(t), \"\" ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return __PRIVATE_collectionParentsStore(e).U(r).next((e => {\n for (const r of e) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (r.collectionId !== t) break;\n n.push(__PRIVATE_decodeResourcePath(r.parent));\n }\n return n;\n }));\n }\n addFieldIndex(e, t) {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const n = __PRIVATE_indexConfigurationStore(e), r = function __PRIVATE_toDbIndexConfiguration(e) {\n return {\n indexId: e.indexId,\n collectionGroup: e.collectionGroup,\n fields: e.fields.map((e => [ e.fieldPath.canonicalString(), e.kind ]))\n };\n }(t);\n delete r.indexId;\n // `indexId` is auto-populated by IndexedDb\n const i = n.add(r);\n if (t.indexState) {\n const n = __PRIVATE_indexStateStore(e);\n return i.next((e => {\n n.put(__PRIVATE_toDbIndexState(e, this.uid, t.indexState.sequenceNumber, t.indexState.offset));\n }));\n }\n return i.next();\n }\n deleteFieldIndex(e, t) {\n const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e), i = __PRIVATE_indexEntriesStore(e);\n return n.delete(t.indexId).next((() => r.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0))));\n }\n deleteAllFieldIndexes(e) {\n const t = __PRIVATE_indexConfigurationStore(e), n = __PRIVATE_indexEntriesStore(e), r = __PRIVATE_indexStateStore(e);\n return t.j().next((() => n.j())).next((() => r.j()));\n }\n createTargetIndexes(e, t) {\n return PersistencePromise.forEach(this.hn(t), (t => this.getIndexType(e, t).next((n => {\n if (0 /* IndexType.NONE */ === n || 1 /* IndexType.PARTIAL */ === n) {\n const n = new __PRIVATE_TargetIndexMatcher(t).an();\n if (null != n) return this.addFieldIndex(e, n);\n }\n }))));\n }\n getDocumentsMatchingTarget(e, t) {\n const n = __PRIVATE_indexEntriesStore(e);\n let r = !0;\n const i = new Map;\n return PersistencePromise.forEach(this.hn(t), (t => this.Pn(e, t).next((e => {\n r && (r = !!e), i.set(t, e);\n })))).next((() => {\n if (r) {\n let e = __PRIVATE_documentKeySet();\n const r = [];\n return PersistencePromise.forEach(i, ((i, s) => {\n __PRIVATE_logDebug(\"IndexedDbIndexManager\", `Using index ${function __PRIVATE_fieldIndexToString(e) {\n return `id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e => `${e.fieldPath}:${e.kind}`)).join(\",\")}`;\n }(i)} to execute ${__PRIVATE_canonifyTarget(t)}`);\n const o = function __PRIVATE_targetGetArrayValues(e, t) {\n const n = __PRIVATE_fieldIndexGetArraySegment(t);\n if (void 0 === n) return null;\n for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, n.fieldPath)) switch (t.op) {\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n return t.value.arrayValue.values || [];\n\n case \"array-contains\" /* Operator.ARRAY_CONTAINS */ :\n return [ t.value ];\n // Remaining filters are not array filters.\n }\n return null;\n }\n /**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */ (s, i), _ = function __PRIVATE_targetGetNotInValues(e, t) {\n const n = new Map;\n for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(t)) for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, r.fieldPath)) switch (t.op) {\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n n.set(r.fieldPath.canonicalString(), t.value);\n break;\n\n case \"not-in\" /* Operator.NOT_IN */ :\n case \"!=\" /* Operator.NOT_EQUAL */ :\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n return n.set(r.fieldPath.canonicalString(), t.value), Array.from(n.values());\n // Remaining filters cannot be used as notIn bounds.\n }\n return null;\n }\n /**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */ (s, i), a = function __PRIVATE_targetGetLowerBound(e, t) {\n const n = [];\n let r = !0;\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) {\n const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.startAt) : __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.startAt);\n n.push(t.value), r && (r = t.inclusive);\n }\n return new Bound(n, r);\n }\n /**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */ (s, i), u = function __PRIVATE_targetGetUpperBound(e, t) {\n const n = [];\n let r = !0;\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) {\n const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.endAt) : __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.endAt);\n n.push(t.value), r && (r = t.inclusive);\n }\n return new Bound(n, r);\n }(s, i), c = this.In(i, s, a), l = this.In(i, s, u), h = this.Tn(i, s, _), P = this.En(i.indexId, o, c, a.inclusive, l, u.inclusive, h);\n return PersistencePromise.forEach(P, (i => n.G(i, t.limit).next((t => {\n t.forEach((t => {\n const n = DocumentKey.fromSegments(t.documentKey);\n e.has(n) || (e = e.add(n), r.push(n));\n }));\n }))));\n })).next((() => r));\n }\n return PersistencePromise.resolve(null);\n }));\n }\n hn(e) {\n let t = this.ln.get(e);\n if (t) return t;\n if (0 === e.filters.length) t = [ e ]; else {\n t = __PRIVATE_getDnfTerms(CompositeFilter.create(e.filters, \"and\" /* CompositeOperator.AND */)).map((t => __PRIVATE_newTarget(e.path, e.collectionGroup, e.orderBy, t.getFilters(), e.limit, e.startAt, e.endAt)));\n }\n return this.ln.set(e, t), t;\n }\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */ En(e, t, n, r, i, s, o) {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const _ = (null != t ? t.length : 1) * Math.max(n.length, i.length), a = _ / (null != t ? t.length : 1), u = [];\n for (let c = 0; c < _; ++c) {\n const _ = t ? this.dn(t[c / a]) : Ae, l = this.An(e, _, n[c % a], r), h = this.Rn(e, _, i[c % a], s), P = o.map((t => this.An(e, _, t, \n /* inclusive= */ !0)));\n u.push(...this.createRange(l, h, P));\n }\n return u;\n }\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */ An(e, t, n, r) {\n const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);\n return r ? i : i.Zt();\n }\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */ Rn(e, t, n, r) {\n const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);\n return r ? i.Zt() : i;\n }\n Pn(e, t) {\n const n = new __PRIVATE_TargetIndexMatcher(t), r = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment();\n return this.getFieldIndexes(e, r).next((e => {\n // Return the index with the most number of segments.\n let t = null;\n for (const r of e) {\n n.rn(r) && (!t || r.fields.length > t.fields.length) && (t = r);\n }\n return t;\n }));\n }\n getIndexType(e, t) {\n let n = 2 /* IndexType.FULL */;\n const r = this.hn(t);\n return PersistencePromise.forEach(r, (t => this.Pn(e, t).next((e => {\n e ? 0 /* IndexType.NONE */ !== n && e.fields.length < function __PRIVATE_targetGetSegmentCount(e) {\n let t = new SortedSet(FieldPath$1.comparator), n = !1;\n for (const r of e.filters) for (const e of r.getFlattenedFilters()) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n e.field.isKeyField() || (\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e.op ? n = !0 : t = t.add(e.field));\n for (const n of e.orderBy) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n n.field.isKeyField() || (t = t.add(n.field));\n return t.size + (n ? 1 : 0);\n }(t) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;\n })))).next((() => \n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n function __PRIVATE_targetHasLimit(e) {\n return null !== e.limit;\n }(t) && r.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));\n }\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */ Vn(e, t) {\n const n = new __PRIVATE_IndexByteEncoder;\n for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {\n const e = t.data.field(r.fieldPath);\n if (null == e) return null;\n const i = n.Yt(r.kind);\n __PRIVATE_FirestoreIndexValueWriter.vt.It(e, i);\n }\n return n.zt();\n }\n /** Encodes a single value to the ascending index format. */ dn(e) {\n const t = new __PRIVATE_IndexByteEncoder;\n return __PRIVATE_FirestoreIndexValueWriter.vt.It(e, t.Yt(0 /* IndexKind.ASCENDING */)), \n t.zt();\n }\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */ mn(e, t) {\n const n = new __PRIVATE_IndexByteEncoder;\n return __PRIVATE_FirestoreIndexValueWriter.vt.It(__PRIVATE_refValue(this.databaseId, t), n.Yt(function __PRIVATE_fieldIndexGetKeyOrder(e) {\n const t = __PRIVATE_fieldIndexGetDirectionalSegments(e);\n return 0 === t.length ? 0 /* IndexKind.ASCENDING */ : t[t.length - 1].kind;\n }(e))), n.zt();\n }\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */ Tn(e, t, n) {\n if (null === n) return [];\n let r = [];\n r.push(new __PRIVATE_IndexByteEncoder);\n let i = 0;\n for (const s of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {\n const e = n[i++];\n for (const n of r) if (this.fn(t, s.fieldPath) && isArray(e)) r = this.gn(r, s, e); else {\n const t = n.Yt(s.kind);\n __PRIVATE_FirestoreIndexValueWriter.vt.It(e, t);\n }\n }\n return this.pn(r);\n }\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */ In(e, t, n) {\n return this.Tn(e, t, n.position);\n }\n /** Returns the byte representation for the provided encoders. */ pn(e) {\n const t = [];\n for (let n = 0; n < e.length; ++n) t[n] = e[n].zt();\n return t;\n }\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */ gn(e, t, n) {\n const r = [ ...e ], i = [];\n for (const e of n.arrayValue.values || []) for (const n of r) {\n const r = new __PRIVATE_IndexByteEncoder;\n r.seed(n.zt()), __PRIVATE_FirestoreIndexValueWriter.vt.It(e, r.Yt(t.kind)), i.push(r);\n }\n return i;\n }\n fn(e, t) {\n return !!e.filters.find((e => e instanceof FieldFilter && e.field.isEqual(t) && (\"in\" /* Operator.IN */ === e.op || \"not-in\" /* Operator.NOT_IN */ === e.op)));\n }\n getFieldIndexes(e, t) {\n const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e);\n return (t ? n.U(\"collectionGroupIndex\", IDBKeyRange.bound(t, t)) : n.U()).next((e => {\n const t = [];\n return PersistencePromise.forEach(e, (e => r.get([ e.indexId, this.uid ]).next((n => {\n t.push(function __PRIVATE_fromDbIndexConfiguration(e, t) {\n const n = t ? new IndexState(t.sequenceNumber, new IndexOffset(__PRIVATE_fromDbTimestamp(t.readTime), new DocumentKey(__PRIVATE_decodeResourcePath(t.documentKey)), t.largestBatchId)) : IndexState.empty(), r = e.fields.map((([e, t]) => new IndexSegment(FieldPath$1.fromServerFormat(e), t)));\n return new FieldIndex(e.indexId, e.collectionGroup, r, n);\n }(e, n));\n })))).next((() => t));\n }));\n }\n getNextCollectionGroupToUpdate(e) {\n return this.getFieldIndexes(e).next((e => 0 === e.length ? null : (e.sort(((e, t) => {\n const n = e.indexState.sequenceNumber - t.indexState.sequenceNumber;\n return 0 !== n ? n : __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);\n })), e[0].collectionGroup)));\n }\n updateCollectionGroup(e, t, n) {\n const r = __PRIVATE_indexConfigurationStore(e), i = __PRIVATE_indexStateStore(e);\n return this.yn(e).next((e => r.U(\"collectionGroupIndex\", IDBKeyRange.bound(t, t)).next((t => PersistencePromise.forEach(t, (t => i.put(__PRIVATE_toDbIndexState(t.indexId, this.uid, e, n))))))));\n }\n updateIndexEntries(e, t) {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const n = new Map;\n return PersistencePromise.forEach(t, ((t, r) => {\n const i = n.get(t.collectionGroup);\n return (i ? PersistencePromise.resolve(i) : this.getFieldIndexes(e, t.collectionGroup)).next((i => (n.set(t.collectionGroup, i), \n PersistencePromise.forEach(i, (n => this.wn(e, t, n).next((t => {\n const i = this.Sn(r, n);\n return t.isEqual(i) ? PersistencePromise.resolve() : this.bn(e, r, n, t, i);\n })))))));\n }));\n }\n Dn(e, t, n, r) {\n return __PRIVATE_indexEntriesStore(e).put({\n indexId: r.indexId,\n uid: this.uid,\n arrayValue: r.arrayValue,\n directionalValue: r.directionalValue,\n orderedDocumentKey: this.mn(n, t.key),\n documentKey: t.key.path.toArray()\n });\n }\n vn(e, t, n, r) {\n return __PRIVATE_indexEntriesStore(e).delete([ r.indexId, this.uid, r.arrayValue, r.directionalValue, this.mn(n, t.key), t.key.path.toArray() ]);\n }\n wn(e, t, n) {\n const r = __PRIVATE_indexEntriesStore(e);\n let i = new SortedSet(__PRIVATE_indexEntryComparator);\n return r.J({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only([ n.indexId, this.uid, this.mn(n, t) ])\n }, ((e, r) => {\n i = i.add(new __PRIVATE_IndexEntry(n.indexId, t, r.arrayValue, r.directionalValue));\n })).next((() => i));\n }\n /** Creates the index entries for the given document. */ Sn(e, t) {\n let n = new SortedSet(__PRIVATE_indexEntryComparator);\n const r = this.Vn(t, e);\n if (null == r) return n;\n const i = __PRIVATE_fieldIndexGetArraySegment(t);\n if (null != i) {\n const s = e.data.field(i.fieldPath);\n if (isArray(s)) for (const i of s.arrayValue.values || []) n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, this.dn(i), r));\n } else n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, Ae, r));\n return n;\n }\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */ bn(e, t, n, r, i) {\n __PRIVATE_logDebug(\"IndexedDbIndexManager\", \"Updating index entries for document '%s'\", t.key);\n const s = [];\n return function __PRIVATE_diffSortedSets(e, t, n, r, i) {\n const s = e.getIterator(), o = t.getIterator();\n let _ = __PRIVATE_advanceIterator(s), a = __PRIVATE_advanceIterator(o);\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n for (;_ || a; ) {\n let e = !1, t = !1;\n if (_ && a) {\n const r = n(_, a);\n r < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n t = !0 : r > 0 && (\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n e = !0);\n } else null != _ ? t = !0 : e = !0;\n e ? (r(a), a = __PRIVATE_advanceIterator(o)) : t ? (i(_), _ = __PRIVATE_advanceIterator(s)) : (_ = __PRIVATE_advanceIterator(s), \n a = __PRIVATE_advanceIterator(o));\n }\n }(r, i, __PRIVATE_indexEntryComparator, (\n /* onAdd= */ r => {\n s.push(this.Dn(e, t, n, r));\n }), (\n /* onRemove= */ r => {\n s.push(this.vn(e, t, n, r));\n })), PersistencePromise.waitFor(s);\n }\n yn(e) {\n let t = 1;\n return __PRIVATE_indexStateStore(e).J({\n index: \"sequenceNumberIndex\",\n reverse: !0,\n range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])\n }, ((e, n, r) => {\n r.done(), t = n.sequenceNumber + 1;\n })).next((() => t));\n }\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */ createRange(e, t, n) {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n n = n.sort(((e, t) => __PRIVATE_indexEntryComparator(e, t))).filter(((e, t, n) => !t || 0 !== __PRIVATE_indexEntryComparator(e, n[t - 1])));\n const r = [];\n r.push(e);\n for (const i of n) {\n const n = __PRIVATE_indexEntryComparator(i, e), s = __PRIVATE_indexEntryComparator(i, t);\n if (0 === n) \n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n r[0] = e.Zt(); else if (n > 0 && s < 0) \n // `notInValue` is in the middle of the range\n r.push(i), r.push(i.Zt()); else if (s > 0) \n // `notInValue` (and all following values) are out of the range\n break;\n }\n r.push(t);\n const i = [];\n for (let e = 0; e < r.length; e += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.Cn(r[e], r[e + 1])) return [];\n const t = [ r[e].indexId, this.uid, r[e].arrayValue, r[e].directionalValue, Ae, [] ], n = [ r[e + 1].indexId, this.uid, r[e + 1].arrayValue, r[e + 1].directionalValue, Ae, [] ];\n i.push(IDBKeyRange.bound(t, n));\n }\n return i;\n }\n Cn(e, t) {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return __PRIVATE_indexEntryComparator(e, t) > 0;\n }\n getMinOffsetFromCollectionGroup(e, t) {\n return this.getFieldIndexes(e, t).next(__PRIVATE_getMinOffsetFromFieldIndexes);\n }\n getMinOffset(e, t) {\n return PersistencePromise.mapArray(this.hn(t), (t => this.Pn(e, t).next((e => e || fail())))).next(__PRIVATE_getMinOffsetFromFieldIndexes);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */ function __PRIVATE_collectionParentsStore(e) {\n return __PRIVATE_getStore(e, \"collectionParents\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */ function __PRIVATE_indexEntriesStore(e) {\n return __PRIVATE_getStore(e, \"indexEntries\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */ function __PRIVATE_indexConfigurationStore(e) {\n return __PRIVATE_getStore(e, \"indexConfiguration\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */ function __PRIVATE_indexStateStore(e) {\n return __PRIVATE_getStore(e, \"indexState\");\n}\n\nfunction __PRIVATE_getMinOffsetFromFieldIndexes(e) {\n __PRIVATE_hardAssert(0 !== e.length);\n let t = e[0].indexState.offset, n = t.largestBatchId;\n for (let r = 1; r < e.length; r++) {\n const i = e[r].indexState.offset;\n __PRIVATE_indexOffsetComparator(i, t) < 0 && (t = i), n < i.largestBatchId && (n = i.largestBatchId);\n }\n return new IndexOffset(t.readTime, t.documentKey, n);\n}\n\n/**\n * @license\n * Copyright 2018 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 */ const Re = {\n didRun: !1,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nclass LruParams {\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n e, \n // The percentage of sequence numbers that we will attempt to collect\n t, \n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n n) {\n this.cacheSizeCollectionThreshold = e, this.percentileToCollect = t, this.maximumSequenceNumbersToCollect = n;\n }\n static withCacheSize(e) {\n return new LruParams(e, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\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/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nfunction removeMutationBatch(e, t, n) {\n const r = e.store(\"mutations\"), i = e.store(\"documentMutations\"), s = [], o = IDBKeyRange.only(n.batchId);\n let _ = 0;\n const a = r.J({\n range: o\n }, ((e, t, n) => (_++, n.delete())));\n s.push(a.next((() => {\n __PRIVATE_hardAssert(1 === _);\n })));\n const u = [];\n for (const e of n.mutations) {\n const r = __PRIVATE_newDbDocumentMutationKey(t, e.key.path, n.batchId);\n s.push(i.delete(r)), u.push(e.key);\n }\n return PersistencePromise.waitFor(s).next((() => u));\n}\n\n/**\n * Returns an approximate size for the given document.\n */ function __PRIVATE_dbDocumentSize(e) {\n if (!e) return 0;\n let t;\n if (e.document) t = e.document; else if (e.unknownDocument) t = e.unknownDocument; else {\n if (!e.noDocument) throw fail();\n t = e.noDocument;\n }\n return JSON.stringify(t).length;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A mutation queue for a specific user, backed by IndexedDB. */ LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, \nLruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, LruParams.DEFAULT = new LruParams(41943040, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), \nLruParams.DISABLED = new LruParams(-1, 0, 0);\n\nclass __PRIVATE_IndexedDbMutationQueue {\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n e, t, n, r) {\n this.userId = e, this.serializer = t, this.indexManager = n, this.referenceDelegate = r, \n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n this.Fn = {};\n }\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */ static lt(e, t, n, r) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n __PRIVATE_hardAssert(\"\" !== e.uid);\n const i = e.isAuthenticated() ? e.uid : \"\";\n return new __PRIVATE_IndexedDbMutationQueue(i, t, n, r);\n }\n checkEmpty(e) {\n let t = !0;\n const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return __PRIVATE_mutationsStore(e).J({\n index: \"userMutationsIndex\",\n range: n\n }, ((e, n, r) => {\n t = !1, r.done();\n })).next((() => t));\n }\n addMutationBatch(e, t, n, r) {\n const i = __PRIVATE_documentMutationsStore(e), s = __PRIVATE_mutationsStore(e);\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return s.add({}).next((o => {\n __PRIVATE_hardAssert(\"number\" == typeof o);\n const _ = new MutationBatch(o, t, n, r), a = function __PRIVATE_toDbMutationBatch(e, t, n) {\n const r = n.baseMutations.map((t => toMutation(e.ct, t))), i = n.mutations.map((t => toMutation(e.ct, t)));\n return {\n userId: t,\n batchId: n.batchId,\n localWriteTimeMs: n.localWriteTime.toMillis(),\n baseMutations: r,\n mutations: i\n };\n }(this.serializer, this.userId, _), u = [];\n let c = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString())));\n for (const e of r) {\n const t = __PRIVATE_newDbDocumentMutationKey(this.userId, e.key.path, o);\n c = c.add(e.key.path.popLast()), u.push(s.put(a)), u.push(i.put(t, x));\n }\n return c.forEach((t => {\n u.push(this.indexManager.addToCollectionParentIndex(e, t));\n })), e.addOnCommittedListener((() => {\n this.Fn[o] = _.keys();\n })), PersistencePromise.waitFor(u).next((() => _));\n }));\n }\n lookupMutationBatch(e, t) {\n return __PRIVATE_mutationsStore(e).get(t).next((e => e ? (__PRIVATE_hardAssert(e.userId === this.userId), \n __PRIVATE_fromDbMutationBatch(this.serializer, e)) : null));\n }\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n Mn(e, t) {\n return this.Fn[t] ? PersistencePromise.resolve(this.Fn[t]) : this.lookupMutationBatch(e, t).next((e => {\n if (e) {\n const n = e.keys();\n return this.Fn[t] = n, n;\n }\n return null;\n }));\n }\n getNextMutationBatchAfterBatchId(e, t) {\n const n = t + 1, r = IDBKeyRange.lowerBound([ this.userId, n ]);\n let i = null;\n return __PRIVATE_mutationsStore(e).J({\n index: \"userMutationsIndex\",\n range: r\n }, ((e, t, r) => {\n t.userId === this.userId && (__PRIVATE_hardAssert(t.batchId >= n), i = __PRIVATE_fromDbMutationBatch(this.serializer, t)), \n r.done();\n })).next((() => i));\n }\n getHighestUnacknowledgedBatchId(e) {\n const t = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);\n let n = -1;\n return __PRIVATE_mutationsStore(e).J({\n index: \"userMutationsIndex\",\n range: t,\n reverse: !0\n }, ((e, t, r) => {\n n = t.batchId, r.done();\n })).next((() => n));\n }\n getAllMutationBatches(e) {\n const t = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return __PRIVATE_mutationsStore(e).U(\"userMutationsIndex\", t).next((e => e.map((e => __PRIVATE_fromDbMutationBatch(this.serializer, e)))));\n }\n getAllMutationBatchesAffectingDocumentKey(e, t) {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const n = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), r = IDBKeyRange.lowerBound(n), i = [];\n return __PRIVATE_documentMutationsStore(e).J({\n range: r\n }, ((n, r, s) => {\n const [o, _, a] = n, u = __PRIVATE_decodeResourcePath(_);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n if (o === this.userId && t.path.isEqual(u)) \n // Look up the mutation batch in the store.\n return __PRIVATE_mutationsStore(e).get(a).next((e => {\n if (!e) throw fail();\n __PRIVATE_hardAssert(e.userId === this.userId), i.push(__PRIVATE_fromDbMutationBatch(this.serializer, e));\n }));\n s.done();\n })).next((() => i));\n }\n getAllMutationBatchesAffectingDocumentKeys(e, t) {\n let n = new SortedSet(__PRIVATE_primitiveComparator);\n const r = [];\n return t.forEach((t => {\n const i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), s = IDBKeyRange.lowerBound(i), o = __PRIVATE_documentMutationsStore(e).J({\n range: s\n }, ((e, r, i) => {\n const [s, o, _] = e, a = __PRIVATE_decodeResourcePath(o);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n s === this.userId && t.path.isEqual(a) ? n = n.add(_) : i.done();\n }));\n r.push(o);\n })), PersistencePromise.waitFor(r).next((() => this.xn(e, n)));\n }\n getAllMutationBatchesAffectingQuery(e, t) {\n const n = t.path, r = n.length + 1, i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n), s = IDBKeyRange.lowerBound(i);\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let o = new SortedSet(__PRIVATE_primitiveComparator);\n return __PRIVATE_documentMutationsStore(e).J({\n range: s\n }, ((e, t, i) => {\n const [s, _, a] = e, u = __PRIVATE_decodeResourcePath(_);\n s === this.userId && n.isPrefixOf(u) ? \n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n u.length === r && (o = o.add(a)) : i.done();\n })).next((() => this.xn(e, o)));\n }\n xn(e, t) {\n const n = [], r = [];\n // TODO(rockwood): Implement this using iterate.\n return t.forEach((t => {\n r.push(__PRIVATE_mutationsStore(e).get(t).next((e => {\n if (null === e) throw fail();\n __PRIVATE_hardAssert(e.userId === this.userId), n.push(__PRIVATE_fromDbMutationBatch(this.serializer, e));\n })));\n })), PersistencePromise.waitFor(r).next((() => n));\n }\n removeMutationBatch(e, t) {\n return removeMutationBatch(e._e, this.userId, t).next((n => (e.addOnCommittedListener((() => {\n this.On(t.batchId);\n })), PersistencePromise.forEach(n, (t => this.referenceDelegate.markPotentiallyOrphaned(e, t))))));\n }\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n On(e) {\n delete this.Fn[e];\n }\n performConsistencyCheck(e) {\n return this.checkEmpty(e).next((t => {\n if (!t) return PersistencePromise.resolve();\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const n = IDBKeyRange.lowerBound(\n /**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\n function __PRIVATE_newDbDocumentMutationPrefixForUser(e) {\n return [ e ];\n }(this.userId)), r = [];\n return __PRIVATE_documentMutationsStore(e).J({\n range: n\n }, ((e, t, n) => {\n if (e[0] === this.userId) {\n const t = __PRIVATE_decodeResourcePath(e[1]);\n r.push(t);\n } else n.done();\n })).next((() => {\n __PRIVATE_hardAssert(0 === r.length);\n }));\n }));\n }\n containsKey(e, t) {\n return __PRIVATE_mutationQueueContainsKey(e, this.userId, t);\n }\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n Nn(e) {\n return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e => e || {\n userId: this.userId,\n lastAcknowledgedBatchId: -1,\n lastStreamToken: \"\"\n }));\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */ function __PRIVATE_mutationQueueContainsKey(e, t, n) {\n const r = __PRIVATE_newDbDocumentMutationPrefixForPath(t, n.path), i = r[1], s = IDBKeyRange.lowerBound(r);\n let o = !1;\n return __PRIVATE_documentMutationsStore(e).J({\n range: s,\n H: !0\n }, ((e, n, r) => {\n const [s, _, /*batchID*/ a] = e;\n s === t && _ === i && (o = !0), r.done();\n })).next((() => o));\n}\n\n/** Returns true if any mutation queue contains the given document. */\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction __PRIVATE_mutationsStore(e) {\n return __PRIVATE_getStore(e, \"mutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function __PRIVATE_documentMutationsStore(e) {\n return __PRIVATE_getStore(e, \"documentMutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function __PRIVATE_mutationQueuesStore(e) {\n return __PRIVATE_getStore(e, \"mutationQueues\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Offset to ensure non-overlapping target ids. */\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nclass __PRIVATE_TargetIdGenerator {\n constructor(e) {\n this.Ln = e;\n }\n next() {\n return this.Ln += 2, this.Ln;\n }\n static Bn() {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new __PRIVATE_TargetIdGenerator(0);\n }\n static kn() {\n // Sync engine assigns target IDs for limbo document detection.\n return new __PRIVATE_TargetIdGenerator(-1);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_IndexedDbTargetCache {\n constructor(e, t) {\n this.referenceDelegate = e, this.serializer = t;\n }\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n allocateTargetId(e) {\n return this.qn(e).next((t => {\n const n = new __PRIVATE_TargetIdGenerator(t.highestTargetId);\n return t.highestTargetId = n.next(), this.Qn(e, t).next((() => t.highestTargetId));\n }));\n }\n getLastRemoteSnapshotVersion(e) {\n return this.qn(e).next((e => SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds, e.lastRemoteSnapshotVersion.nanoseconds))));\n }\n getHighestSequenceNumber(e) {\n return this.qn(e).next((e => e.highestListenSequenceNumber));\n }\n setTargetsMetadata(e, t, n) {\n return this.qn(e).next((r => (r.highestListenSequenceNumber = t, n && (r.lastRemoteSnapshotVersion = n.toTimestamp()), \n t > r.highestListenSequenceNumber && (r.highestListenSequenceNumber = t), this.Qn(e, r))));\n }\n addTargetData(e, t) {\n return this.Kn(e, t).next((() => this.qn(e).next((n => (n.targetCount += 1, this.$n(t, n), \n this.Qn(e, n))))));\n }\n updateTargetData(e, t) {\n return this.Kn(e, t);\n }\n removeTargetData(e, t) {\n return this.removeMatchingKeysForTargetId(e, t.targetId).next((() => __PRIVATE_targetsStore(e).delete(t.targetId))).next((() => this.qn(e))).next((t => (__PRIVATE_hardAssert(t.targetCount > 0), \n t.targetCount -= 1, this.Qn(e, t))));\n }\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */ removeTargets(e, t, n) {\n let r = 0;\n const i = [];\n return __PRIVATE_targetsStore(e).J(((s, o) => {\n const _ = __PRIVATE_fromDbTarget(o);\n _.sequenceNumber <= t && null === n.get(_.targetId) && (r++, i.push(this.removeTargetData(e, _)));\n })).next((() => PersistencePromise.waitFor(i))).next((() => r));\n }\n /**\n * Call provided function with each `TargetData` that we have cached.\n */ forEachTarget(e, t) {\n return __PRIVATE_targetsStore(e).J(((e, n) => {\n const r = __PRIVATE_fromDbTarget(n);\n t(r);\n }));\n }\n qn(e) {\n return __PRIVATE_globalTargetStore(e).get(\"targetGlobalKey\").next((e => (__PRIVATE_hardAssert(null !== e), \n e)));\n }\n Qn(e, t) {\n return __PRIVATE_globalTargetStore(e).put(\"targetGlobalKey\", t);\n }\n Kn(e, t) {\n return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer, t));\n }\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */ $n(e, t) {\n let n = !1;\n return e.targetId > t.highestTargetId && (t.highestTargetId = e.targetId, n = !0), \n e.sequenceNumber > t.highestListenSequenceNumber && (t.highestListenSequenceNumber = e.sequenceNumber, \n n = !0), n;\n }\n getTargetCount(e) {\n return this.qn(e).next((e => e.targetCount));\n }\n getTargetData(e, t) {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const n = __PRIVATE_canonifyTarget(t), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);\n let i = null;\n return __PRIVATE_targetsStore(e).J({\n range: r,\n index: \"queryTargetsIndex\"\n }, ((e, n, r) => {\n const s = __PRIVATE_fromDbTarget(n);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n __PRIVATE_targetEquals(t, s.target) && (i = s, r.done());\n })).next((() => i));\n }\n addMatchingKeys(e, t, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const r = [], i = __PRIVATE_documentTargetStore(e);\n return t.forEach((t => {\n const s = __PRIVATE_encodeResourcePath(t.path);\n r.push(i.put({\n targetId: n,\n path: s\n })), r.push(this.referenceDelegate.addReference(e, n, t));\n })), PersistencePromise.waitFor(r);\n }\n removeMatchingKeys(e, t, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const r = __PRIVATE_documentTargetStore(e);\n return PersistencePromise.forEach(t, (t => {\n const i = __PRIVATE_encodeResourcePath(t.path);\n return PersistencePromise.waitFor([ r.delete([ n, i ]), this.referenceDelegate.removeReference(e, n, t) ]);\n }));\n }\n removeMatchingKeysForTargetId(e, t) {\n const n = __PRIVATE_documentTargetStore(e), r = IDBKeyRange.bound([ t ], [ t + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return n.delete(r);\n }\n getMatchingKeysForTargetId(e, t) {\n const n = IDBKeyRange.bound([ t ], [ t + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0), r = __PRIVATE_documentTargetStore(e);\n let i = __PRIVATE_documentKeySet();\n return r.J({\n range: n,\n H: !0\n }, ((e, t, n) => {\n const r = __PRIVATE_decodeResourcePath(e[1]), s = new DocumentKey(r);\n i = i.add(s);\n })).next((() => i));\n }\n containsKey(e, t) {\n const n = __PRIVATE_encodeResourcePath(t.path), r = IDBKeyRange.bound([ n ], [ __PRIVATE_immediateSuccessor(n) ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n let i = 0;\n return __PRIVATE_documentTargetStore(e).J({\n index: \"documentTargetsIndex\",\n H: !0,\n range: r\n }, (([e, t], n, r) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n 0 !== e && (i++, r.done());\n })).next((() => i > 0));\n }\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n ot(e, t) {\n return __PRIVATE_targetsStore(e).get(t).next((e => e ? __PRIVATE_fromDbTarget(e) : null));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */ function __PRIVATE_targetsStore(e) {\n return __PRIVATE_getStore(e, \"targets\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */ function __PRIVATE_globalTargetStore(e) {\n return __PRIVATE_getStore(e, \"targetGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */ function __PRIVATE_documentTargetStore(e) {\n return __PRIVATE_getStore(e, \"targetDocuments\");\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 */ function __PRIVATE_bufferEntryComparator([e, t], [n, r]) {\n const i = __PRIVATE_primitiveComparator(e, n);\n return 0 === i ? __PRIVATE_primitiveComparator(t, r) : i;\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */ class __PRIVATE_RollingSequenceNumberBuffer {\n constructor(e) {\n this.Un = e, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.Wn = 0;\n }\n Gn() {\n return ++this.Wn;\n }\n zn(e) {\n const t = [ e, this.Gn() ];\n if (this.buffer.size < this.Un) this.buffer = this.buffer.add(t); else {\n const e = this.buffer.last();\n __PRIVATE_bufferEntryComparator(t, e) < 0 && (this.buffer = this.buffer.delete(e).add(t));\n }\n }\n get maxValue() {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()[0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */ class __PRIVATE_LruScheduler {\n constructor(e, t, n) {\n this.garbageCollector = e, this.asyncQueue = t, this.localStore = n, this.jn = null;\n }\n start() {\n -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Hn(6e4);\n }\n stop() {\n this.jn && (this.jn.cancel(), this.jn = null);\n }\n get started() {\n return null !== this.jn;\n }\n Hn(e) {\n __PRIVATE_logDebug(\"LruGarbageCollector\", `Garbage collection scheduled in ${e}ms`), \n this.jn = this.asyncQueue.enqueueAfterDelay(\"lru_garbage_collection\" /* TimerId.LruGarbageCollection */ , e, (async () => {\n this.jn = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(\"LruGarbageCollector\", \"Ignoring IndexedDB error during garbage collection: \", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n }\n await this.Hn(3e5);\n }));\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */ class __PRIVATE_LruGarbageCollectorImpl {\n constructor(e, t) {\n this.Jn = e, this.params = t;\n }\n calculateTargetCount(e, t) {\n return this.Jn.Yn(e).next((e => Math.floor(t / 100 * e)));\n }\n nthSequenceNumber(e, t) {\n if (0 === t) return PersistencePromise.resolve(__PRIVATE_ListenSequence.oe);\n const n = new __PRIVATE_RollingSequenceNumberBuffer(t);\n return this.Jn.forEachTarget(e, (e => n.zn(e.sequenceNumber))).next((() => this.Jn.Zn(e, (e => n.zn(e))))).next((() => n.maxValue));\n }\n removeTargets(e, t, n) {\n return this.Jn.removeTargets(e, t, n);\n }\n removeOrphanedDocuments(e, t) {\n return this.Jn.removeOrphanedDocuments(e, t);\n }\n collect(e, t) {\n return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug(\"LruGarbageCollector\", \"Garbage collection skipped; disabled\"), \n PersistencePromise.resolve(Re)) : this.getCacheSize(e).next((n => n < this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug(\"LruGarbageCollector\", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), \n Re) : this.Xn(e, t)));\n }\n getCacheSize(e) {\n return this.Jn.getCacheSize(e);\n }\n Xn(e, t) {\n let n, r, i, s, o, a, u;\n const c = Date.now();\n return this.calculateTargetCount(e, this.params.percentileToCollect).next((t => (\n // Cap at the configured max\n t > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug(\"LruGarbageCollector\", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`), \n r = this.params.maximumSequenceNumbersToCollect) : r = t, s = Date.now(), this.nthSequenceNumber(e, r)))).next((r => (n = r, \n o = Date.now(), this.removeTargets(e, n, t)))).next((t => (i = t, a = Date.now(), \n this.removeOrphanedDocuments(e, n)))).next((e => {\n if (u = Date.now(), __PRIVATE_getLogLevel() <= LogLevel.DEBUG) {\n __PRIVATE_logDebug(\"LruGarbageCollector\", `LRU Garbage Collection\\n\\tCounted targets in ${s - c}ms\\n\\tDetermined least recently used ${r} in ` + (o - s) + \"ms\\n\" + `\\tRemoved ${i} targets in ` + (a - o) + \"ms\\n\" + `\\tRemoved ${e} documents in ` + (u - a) + \"ms\\n\" + `Total Duration: ${u - c}ms`);\n }\n return PersistencePromise.resolve({\n didRun: !0,\n sequenceNumbersCollected: r,\n targetsRemoved: i,\n documentsRemoved: e\n });\n }));\n }\n}\n\nfunction __PRIVATE_newLruGarbageCollector(e, t) {\n return new __PRIVATE_LruGarbageCollectorImpl(e, t);\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/** Provides LRU functionality for IndexedDB persistence. */ class __PRIVATE_IndexedDbLruDelegateImpl {\n constructor(e, t) {\n this.db = e, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);\n }\n Yn(e) {\n const t = this.er(e);\n return this.db.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t))));\n }\n er(e) {\n let t = 0;\n return this.Zn(e, (e => {\n t++;\n })).next((() => t));\n }\n forEachTarget(e, t) {\n return this.db.getTargetCache().forEachTarget(e, t);\n }\n Zn(e, t) {\n return this.tr(e, ((e, n) => t(n)));\n }\n addReference(e, t, n) {\n return __PRIVATE_writeSentinelKey(e, n);\n }\n removeReference(e, t, n) {\n return __PRIVATE_writeSentinelKey(e, n);\n }\n removeTargets(e, t, n) {\n return this.db.getTargetCache().removeTargets(e, t, n);\n }\n markPotentiallyOrphaned(e, t) {\n return __PRIVATE_writeSentinelKey(e, t);\n }\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */ nr(e, t) {\n return function __PRIVATE_mutationQueuesContainKey(e, t) {\n let n = !1;\n return __PRIVATE_mutationQueuesStore(e).Y((r => __PRIVATE_mutationQueueContainsKey(e, r, t).next((e => (e && (n = !0), \n PersistencePromise.resolve(!e)))))).next((() => n));\n }(e, t);\n }\n removeOrphanedDocuments(e, t) {\n const n = this.db.getRemoteDocumentCache().newChangeBuffer(), r = [];\n let i = 0;\n return this.tr(e, ((s, o) => {\n if (o <= t) {\n const t = this.nr(e, s).next((t => {\n if (!t) \n // Our size accounting requires us to read all documents before\n // removing them.\n return i++, n.getEntry(e, s).next((() => (n.removeEntry(s, SnapshotVersion.min()), \n __PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e) {\n return [ 0, __PRIVATE_encodeResourcePath(e.path) ];\n }\n /**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */ (s)))));\n }));\n r.push(t);\n }\n })).next((() => PersistencePromise.waitFor(r))).next((() => n.apply(e))).next((() => i));\n }\n removeTarget(e, t) {\n const n = t.withSequenceNumber(e.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(e, n);\n }\n updateLimboDocument(e, t) {\n return __PRIVATE_writeSentinelKey(e, t);\n }\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */ tr(e, t) {\n const n = __PRIVATE_documentTargetStore(e);\n let r, i = __PRIVATE_ListenSequence.oe;\n return n.J({\n index: \"documentTargetsIndex\"\n }, (([e, n], {path: s, sequenceNumber: o}) => {\n 0 === e ? (\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n i !== __PRIVATE_ListenSequence.oe && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i), \n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n i = o, r = s) : \n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n i = __PRIVATE_ListenSequence.oe;\n })).next((() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n i !== __PRIVATE_ListenSequence.oe && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i);\n }));\n }\n getCacheSize(e) {\n return this.db.getRemoteDocumentCache().getSize(e);\n }\n}\n\nfunction __PRIVATE_writeSentinelKey(e, t) {\n return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e, t) {\n return {\n targetId: 0,\n path: __PRIVATE_encodeResourcePath(e.path),\n sequenceNumber: t\n };\n }(t, e.currentSequenceNumber));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */ class RemoteDocumentChangeBuffer {\n constructor() {\n // A mapping of document key to the new cache entry that should be written.\n this.changes = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))), this.changesApplied = !1;\n }\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ addEntry(e) {\n this.assertNotApplied(), this.changes.set(e.key, e);\n }\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ removeEntry(e, t) {\n this.assertNotApplied(), this.changes.set(e, MutableDocument.newInvalidDocument(e).setReadTime(t));\n }\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */ getEntry(e, t) {\n this.assertNotApplied();\n const n = this.changes.get(t);\n return void 0 !== n ? PersistencePromise.resolve(n) : this.getFromCache(e, t);\n }\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */ getEntries(e, t) {\n return this.getAllFromCache(e, t);\n }\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */ apply(e) {\n return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(e);\n }\n /** Helper to assert this.changes is not null */ assertNotApplied() {}\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */ class __PRIVATE_IndexedDbRemoteDocumentCacheImpl {\n constructor(e) {\n this.serializer = e;\n }\n setIndexManager(e) {\n this.indexManager = e;\n }\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ addEntry(e, t, n) {\n return __PRIVATE_remoteDocumentsStore(e).put(n);\n }\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ removeEntry(e, t, n) {\n return __PRIVATE_remoteDocumentsStore(e).delete(\n /**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\n function __PRIVATE_dbReadTimeKey(e, t) {\n const n = e.path.toArray();\n return [ \n /* prefix path */ n.slice(0, n.length - 2), \n /* collection id */ n[n.length - 2], __PRIVATE_toDbTimestampKey(t), \n /* document id */ n[n.length - 1] ];\n }\n /**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */ (t, n));\n }\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */ updateMetadata(e, t) {\n return this.getMetadata(e).next((n => (n.byteSize += t, this.rr(e, n))));\n }\n getEntry(e, t) {\n let n = MutableDocument.newInvalidDocument(t);\n return __PRIVATE_remoteDocumentsStore(e).J({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(__PRIVATE_dbKey(t))\n }, ((e, r) => {\n n = this.ir(t, r);\n })).next((() => n));\n }\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */ sr(e, t) {\n let n = {\n size: 0,\n document: MutableDocument.newInvalidDocument(t)\n };\n return __PRIVATE_remoteDocumentsStore(e).J({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(__PRIVATE_dbKey(t))\n }, ((e, r) => {\n n = {\n document: this.ir(t, r),\n size: __PRIVATE_dbDocumentSize(r)\n };\n })).next((() => n));\n }\n getEntries(e, t) {\n let n = __PRIVATE_mutableDocumentMap();\n return this._r(e, t, ((e, t) => {\n const r = this.ir(e, t);\n n = n.insert(e, r);\n })).next((() => n));\n }\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */ ar(e, t) {\n let n = __PRIVATE_mutableDocumentMap(), r = new SortedMap(DocumentKey.comparator);\n return this._r(e, t, ((e, t) => {\n const i = this.ir(e, t);\n n = n.insert(e, i), r = r.insert(e, __PRIVATE_dbDocumentSize(t));\n })).next((() => ({\n documents: n,\n ur: r\n })));\n }\n _r(e, t, n) {\n if (t.isEmpty()) return PersistencePromise.resolve();\n let r = new SortedSet(__PRIVATE_dbKeyComparator);\n t.forEach((e => r = r.add(e)));\n const i = IDBKeyRange.bound(__PRIVATE_dbKey(r.first()), __PRIVATE_dbKey(r.last())), s = r.getIterator();\n let o = s.getNext();\n return __PRIVATE_remoteDocumentsStore(e).J({\n index: \"documentKeyIndex\",\n range: i\n }, ((e, t, r) => {\n const i = DocumentKey.fromSegments([ ...t.prefixPath, t.collectionGroup, t.documentId ]);\n // Go through keys not found in cache.\n for (;o && __PRIVATE_dbKeyComparator(o, i) < 0; ) n(o, null), o = s.getNext();\n o && o.isEqual(i) && (\n // Key found in cache.\n n(o, t), o = s.hasNext() ? s.getNext() : null), \n // Skip to the next key (if there is one).\n o ? r.$(__PRIVATE_dbKey(o)) : r.done();\n })).next((() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n for (;o; ) n(o, null), o = s.hasNext() ? s.getNext() : null;\n }));\n }\n getDocumentsMatchingQuery(e, t, n, r, i) {\n const s = t.path, o = [ s.popLast().toArray(), s.lastSegment(), __PRIVATE_toDbTimestampKey(n.readTime), n.documentKey.path.isEmpty() ? \"\" : n.documentKey.path.lastSegment() ], _ = [ s.popLast().toArray(), s.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], \"\" ];\n return __PRIVATE_remoteDocumentsStore(e).U(IDBKeyRange.bound(o, _, !0)).next((e => {\n null == i || i.incrementDocumentReadCount(e.length);\n let n = __PRIVATE_mutableDocumentMap();\n for (const i of e) {\n const e = this.ir(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i);\n e.isFoundDocument() && (__PRIVATE_queryMatches(t, e) || r.has(e.key)) && (\n // Either the document matches the given query, or it is mutated.\n n = n.insert(e.key, e));\n }\n return n;\n }));\n }\n getAllFromCollectionGroup(e, t, n, r) {\n let i = __PRIVATE_mutableDocumentMap();\n const s = __PRIVATE_dbCollectionGroupKey(t, n), o = __PRIVATE_dbCollectionGroupKey(t, IndexOffset.max());\n return __PRIVATE_remoteDocumentsStore(e).J({\n index: \"collectionGroupIndex\",\n range: IDBKeyRange.bound(s, o, !0)\n }, ((e, t, n) => {\n const s = this.ir(DocumentKey.fromSegments(t.prefixPath.concat(t.collectionGroup, t.documentId)), t);\n i = i.insert(s.key, s), i.size === r && n.done();\n })).next((() => i));\n }\n newChangeBuffer(e) {\n return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e && e.trackRemovals);\n }\n getSize(e) {\n return this.getMetadata(e).next((e => e.byteSize));\n }\n getMetadata(e) {\n return __PRIVATE_documentGlobalStore(e).get(\"remoteDocumentGlobalKey\").next((e => (__PRIVATE_hardAssert(!!e), \n e)));\n }\n rr(e, t) {\n return __PRIVATE_documentGlobalStore(e).put(\"remoteDocumentGlobalKey\", t);\n }\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */ ir(e, t) {\n if (t) {\n const e = __PRIVATE_fromDbRemoteDocument(this.serializer, t);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n if (!(e.isNoDocument() && e.version.isEqual(SnapshotVersion.min()))) return e;\n }\n return MutableDocument.newInvalidDocument(e);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */ function __PRIVATE_newIndexedDbRemoteDocumentCache(e) {\n return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */ class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(e, t) {\n super(), this.cr = e, this.trackRemovals = t, \n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n this.lr = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t)));\n }\n applyChanges(e) {\n const t = [];\n let n = 0, r = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString())));\n return this.changes.forEach(((i, s) => {\n const o = this.lr.get(i);\n if (t.push(this.cr.removeEntry(e, i, o.readTime)), s.isValidDocument()) {\n const _ = __PRIVATE_toDbRemoteDocument(this.cr.serializer, s);\n r = r.add(i.path.popLast());\n const a = __PRIVATE_dbDocumentSize(_);\n n += a - o.size, t.push(this.cr.addEntry(e, i, _));\n } else if (n -= o.size, this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const n = __PRIVATE_toDbRemoteDocument(this.cr.serializer, s.convertToNoDocument(SnapshotVersion.min()));\n t.push(this.cr.addEntry(e, i, n));\n }\n })), r.forEach((n => {\n t.push(this.cr.indexManager.addToCollectionParentIndex(e, n));\n })), t.push(this.cr.updateMetadata(e, n)), PersistencePromise.waitFor(t);\n }\n getFromCache(e, t) {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.cr.sr(e, t).next((e => (this.lr.set(t, {\n size: e.size,\n readTime: e.document.readTime\n }), e.document)));\n }\n getAllFromCache(e, t) {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.cr.ar(e, t).next((({documents: e, ur: t}) => (\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n t.forEach(((t, n) => {\n this.lr.set(t, {\n size: n,\n readTime: e.get(t).readTime\n });\n })), e)));\n }\n}\n\nfunction __PRIVATE_documentGlobalStore(e) {\n return __PRIVATE_getStore(e, \"remoteDocumentGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */ function __PRIVATE_remoteDocumentsStore(e) {\n return __PRIVATE_getStore(e, \"remoteDocumentsV14\");\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */ function __PRIVATE_dbKey(e) {\n const t = e.path.toArray();\n return [ \n /* prefix path */ t.slice(0, t.length - 2), \n /* collection id */ t[t.length - 2], \n /* document id */ t[t.length - 1] ];\n}\n\nfunction __PRIVATE_dbCollectionGroupKey(e, t) {\n const n = t.documentKey.path.toArray();\n return [ \n /* collection id */ e, __PRIVATE_toDbTimestampKey(t.readTime), \n /* prefix path */ n.slice(0, n.length - 2), \n /* document id */ n.length > 0 ? n[n.length - 1] : \"\" ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */ function __PRIVATE_dbKeyComparator(e, t) {\n const n = e.path.toArray(), r = t.path.toArray();\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let i = 0;\n for (let e = 0; e < n.length - 2 && e < r.length - 2; ++e) if (i = __PRIVATE_primitiveComparator(n[e], r[e]), \n i) return i;\n return i = __PRIVATE_primitiveComparator(n.length, r.length), i || (i = __PRIVATE_primitiveComparator(n[n.length - 2], r[r.length - 2]), \n i || __PRIVATE_primitiveComparator(n[n.length - 1], r[r.length - 1]));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n * 16. Parse timestamp strings before creating index entries.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nclass OverlayedDocument {\n constructor(e, \n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n t) {\n this.overlayedDocument = e, this.mutatedFields = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */ class LocalDocumentsView {\n constructor(e, t, n, r) {\n this.remoteDocumentCache = e, this.mutationQueue = t, this.documentOverlayCache = n, \n this.indexManager = r;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */ getDocument(e, t) {\n let n = null;\n return this.documentOverlayCache.getOverlay(e, t).next((r => (n = r, this.remoteDocumentCache.getEntry(e, t)))).next((e => (null !== n && __PRIVATE_mutationApplyToLocalView(n.mutation, e, FieldMask.empty(), Timestamp.now()), \n e)));\n }\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */ getDocuments(e, t) {\n return this.remoteDocumentCache.getEntries(e, t).next((t => this.getLocalViewOfDocuments(e, t, __PRIVATE_documentKeySet()).next((() => t))));\n }\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */ getLocalViewOfDocuments(e, t, n = __PRIVATE_documentKeySet()) {\n const r = __PRIVATE_newOverlayMap();\n return this.populateOverlays(e, r, t).next((() => this.computeViews(e, t, r, n).next((e => {\n let t = documentMap();\n return e.forEach(((e, n) => {\n t = t.insert(e, n.overlayedDocument);\n })), t;\n }))));\n }\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */ getOverlayedDocuments(e, t) {\n const n = __PRIVATE_newOverlayMap();\n return this.populateOverlays(e, n, t).next((() => this.computeViews(e, t, n, __PRIVATE_documentKeySet())));\n }\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */ populateOverlays(e, t, n) {\n const r = [];\n return n.forEach((e => {\n t.has(e) || r.push(e);\n })), this.documentOverlayCache.getOverlays(e, r).next((e => {\n e.forEach(((e, n) => {\n t.set(e, n);\n }));\n }));\n }\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */ computeViews(e, t, n, r) {\n let i = __PRIVATE_mutableDocumentMap();\n const s = __PRIVATE_newDocumentKeyMap(), o = function __PRIVATE_newOverlayedDocumentMap() {\n return __PRIVATE_newDocumentKeyMap();\n }();\n return t.forEach(((e, t) => {\n const o = n.get(t.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n r.has(t.key) && (void 0 === o || o.mutation instanceof __PRIVATE_PatchMutation) ? i = i.insert(t.key, t) : void 0 !== o ? (s.set(t.key, o.mutation.getFieldMask()), \n __PRIVATE_mutationApplyToLocalView(o.mutation, t, o.mutation.getFieldMask(), Timestamp.now())) : \n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n s.set(t.key, FieldMask.empty());\n })), this.recalculateAndSaveOverlays(e, i).next((e => (e.forEach(((e, t) => s.set(e, t))), \n t.forEach(((e, t) => {\n var n;\n return o.set(e, new OverlayedDocument(t, null !== (n = s.get(e)) && void 0 !== n ? n : null));\n })), o)));\n }\n recalculateAndSaveOverlays(e, t) {\n const n = __PRIVATE_newDocumentKeyMap();\n // A reverse lookup map from batch id to the documents within that batch.\n let r = new SortedMap(((e, t) => e - t)), i = __PRIVATE_documentKeySet();\n return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e, t).next((e => {\n for (const i of e) i.keys().forEach((e => {\n const s = t.get(e);\n if (null === s) return;\n let o = n.get(e) || FieldMask.empty();\n o = i.applyToLocalView(s, o), n.set(e, o);\n const _ = (r.get(i.batchId) || __PRIVATE_documentKeySet()).add(e);\n r = r.insert(i.batchId, _);\n }));\n })).next((() => {\n const s = [], o = r.getReverseIterator();\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n for (;o.hasNext(); ) {\n const r = o.getNext(), _ = r.key, a = r.value, u = __PRIVATE_newMutationMap();\n a.forEach((e => {\n if (!i.has(e)) {\n const r = __PRIVATE_calculateOverlayMutation(t.get(e), n.get(e));\n null !== r && u.set(e, r), i = i.add(e);\n }\n })), s.push(this.documentOverlayCache.saveOverlays(e, _, u));\n }\n return PersistencePromise.waitFor(s);\n })).next((() => n));\n }\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */ recalculateAndSaveOverlaysForDocumentKeys(e, t) {\n return this.remoteDocumentCache.getEntries(e, t).next((t => this.recalculateAndSaveOverlays(e, t)));\n }\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n * @param context - A optional tracker to keep a record of important details\n * during database local query execution.\n */ getDocumentsMatchingQuery(e, t, n, r) {\n /**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\n return function __PRIVATE_isDocumentQuery$1(e) {\n return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;\n }(t) ? this.getDocumentsMatchingDocumentQuery(e, t.path) : __PRIVATE_isCollectionGroupQuery(t) ? this.getDocumentsMatchingCollectionGroupQuery(e, t, n, r) : this.getDocumentsMatchingCollectionQuery(e, t, n, r);\n }\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n *

    The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */ getNextDocuments(e, t, n, r) {\n return this.remoteDocumentCache.getAllFromCollectionGroup(e, t, n, r).next((i => {\n const s = r - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e, t, n.largestBatchId, r - i.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let o = -1, _ = i;\n return s.next((t => PersistencePromise.forEach(t, ((t, n) => (o < n.largestBatchId && (o = n.largestBatchId), \n i.get(t) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e, t).next((e => {\n _ = _.insert(t, e);\n }))))).next((() => this.populateOverlays(e, t, i))).next((() => this.computeViews(e, _, t, __PRIVATE_documentKeySet()))).next((e => ({\n batchId: o,\n changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e)\n })))));\n }));\n }\n getDocumentsMatchingDocumentQuery(e, t) {\n // Just do a simple document lookup.\n return this.getDocument(e, new DocumentKey(t)).next((e => {\n let t = documentMap();\n return e.isFoundDocument() && (t = t.insert(e.key, e)), t;\n }));\n }\n getDocumentsMatchingCollectionGroupQuery(e, t, n, r) {\n const i = t.collectionGroup;\n let s = documentMap();\n return this.indexManager.getCollectionParents(e, i).next((o => PersistencePromise.forEach(o, (o => {\n const _ = function __PRIVATE_asCollectionQueryAtPath(e, t) {\n return new __PRIVATE_QueryImpl(t, \n /*collectionGroup=*/ null, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);\n }(t, o.child(i));\n return this.getDocumentsMatchingCollectionQuery(e, _, n, r).next((e => {\n e.forEach(((e, t) => {\n s = s.insert(e, t);\n }));\n }));\n })).next((() => s))));\n }\n getDocumentsMatchingCollectionQuery(e, t, n, r) {\n // Query the remote documents and overlay mutations.\n let i;\n return this.documentOverlayCache.getOverlaysForCollection(e, t.path, n.largestBatchId).next((s => (i = s, \n this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, i, r)))).next((e => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n i.forEach(((t, n) => {\n const r = n.getKey();\n null === e.get(r) && (e = e.insert(r, MutableDocument.newInvalidDocument(r)));\n }));\n // Apply the overlays and match against the query.\n let n = documentMap();\n return e.forEach(((e, r) => {\n const s = i.get(e);\n void 0 !== s && __PRIVATE_mutationApplyToLocalView(s.mutation, r, FieldMask.empty(), Timestamp.now()), \n // Finally, insert the documents that still match the query\n __PRIVATE_queryMatches(t, r) && (n = n.insert(e, r));\n })), n;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryBundleCache {\n constructor(e) {\n this.serializer = e, this.hr = new Map, this.Pr = new Map;\n }\n getBundleMetadata(e, t) {\n return PersistencePromise.resolve(this.hr.get(t));\n }\n saveBundleMetadata(e, t) {\n return this.hr.set(t.id, \n /** Decodes a BundleMetadata proto into a BundleMetadata object. */\n function __PRIVATE_fromBundleMetadata(e) {\n return {\n id: e.id,\n version: e.version,\n createTime: __PRIVATE_fromVersion(e.createTime)\n };\n }(t)), PersistencePromise.resolve();\n }\n getNamedQuery(e, t) {\n return PersistencePromise.resolve(this.Pr.get(t));\n }\n saveNamedQuery(e, t) {\n return this.Pr.set(t.name, function __PRIVATE_fromProtoNamedQuery(e) {\n return {\n name: e.name,\n query: __PRIVATE_fromBundledQuery(e.bundledQuery),\n readTime: __PRIVATE_fromVersion(e.readTime)\n };\n }(t)), PersistencePromise.resolve();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */ class __PRIVATE_MemoryDocumentOverlayCache {\n constructor() {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n this.overlays = new SortedMap(DocumentKey.comparator), this.Ir = new Map;\n }\n getOverlay(e, t) {\n return PersistencePromise.resolve(this.overlays.get(t));\n }\n getOverlays(e, t) {\n const n = __PRIVATE_newOverlayMap();\n return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => {\n null !== e && n.set(t, e);\n })))).next((() => n));\n }\n saveOverlays(e, t, n) {\n return n.forEach(((n, r) => {\n this.ht(e, t, r);\n })), PersistencePromise.resolve();\n }\n removeOverlaysForBatchId(e, t, n) {\n const r = this.Ir.get(n);\n return void 0 !== r && (r.forEach((e => this.overlays = this.overlays.remove(e))), \n this.Ir.delete(n)), PersistencePromise.resolve();\n }\n getOverlaysForCollection(e, t, n) {\n const r = __PRIVATE_newOverlayMap(), i = t.length + 1, s = new DocumentKey(t.child(\"\")), o = this.overlays.getIteratorFrom(s);\n for (;o.hasNext(); ) {\n const e = o.getNext().value, s = e.getKey();\n if (!t.isPrefixOf(s.path)) break;\n // Documents from sub-collections\n s.path.length === i && (e.largestBatchId > n && r.set(e.getKey(), e));\n }\n return PersistencePromise.resolve(r);\n }\n getOverlaysForCollectionGroup(e, t, n, r) {\n let i = new SortedMap(((e, t) => e - t));\n const s = this.overlays.getIterator();\n for (;s.hasNext(); ) {\n const e = s.getNext().value;\n if (e.getKey().getCollectionGroup() === t && e.largestBatchId > n) {\n let t = i.get(e.largestBatchId);\n null === t && (t = __PRIVATE_newOverlayMap(), i = i.insert(e.largestBatchId, t)), \n t.set(e.getKey(), e);\n }\n }\n const o = __PRIVATE_newOverlayMap(), _ = i.getIterator();\n for (;_.hasNext(); ) {\n if (_.getNext().value.forEach(((e, t) => o.set(e, t))), o.size() >= r) break;\n }\n return PersistencePromise.resolve(o);\n }\n ht(e, t, n) {\n // Remove the association of the overlay to its batch id.\n const r = this.overlays.get(n.key);\n if (null !== r) {\n const e = this.Ir.get(r.largestBatchId).delete(n.key);\n this.Ir.set(r.largestBatchId, e);\n }\n this.overlays = this.overlays.insert(n.key, new Overlay(t, n));\n // Create the association of this overlay to the given largestBatchId.\n let i = this.Ir.get(t);\n void 0 === i && (i = __PRIVATE_documentKeySet(), this.Ir.set(t, i)), this.Ir.set(t, i.add(n.key));\n }\n}\n\n/**\n * @license\n * Copyright 2024 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 */ class __PRIVATE_MemoryGlobalsCache {\n constructor() {\n this.sessionToken = ByteString.EMPTY_BYTE_STRING;\n }\n getSessionToken(e) {\n return PersistencePromise.resolve(this.sessionToken);\n }\n setSessionToken(e, t) {\n return this.sessionToken = t, PersistencePromise.resolve();\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */ class __PRIVATE_ReferenceSet {\n constructor() {\n // A set of outstanding references to a document sorted by key.\n this.Tr = new SortedSet(__PRIVATE_DocReference.Er), \n // A set of outstanding references to a document sorted by target id.\n this.dr = new SortedSet(__PRIVATE_DocReference.Ar);\n }\n /** Returns true if the reference set contains no references. */ isEmpty() {\n return this.Tr.isEmpty();\n }\n /** Adds a reference to the given document key for the given ID. */ addReference(e, t) {\n const n = new __PRIVATE_DocReference(e, t);\n this.Tr = this.Tr.add(n), this.dr = this.dr.add(n);\n }\n /** Add references to the given document keys for the given ID. */ Rr(e, t) {\n e.forEach((e => this.addReference(e, t)));\n }\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */ removeReference(e, t) {\n this.Vr(new __PRIVATE_DocReference(e, t));\n }\n mr(e, t) {\n e.forEach((e => this.removeReference(e, t)));\n }\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */ gr(e) {\n const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1), i = [];\n return this.dr.forEachInRange([ n, r ], (e => {\n this.Vr(e), i.push(e.key);\n })), i;\n }\n pr() {\n this.Tr.forEach((e => this.Vr(e)));\n }\n Vr(e) {\n this.Tr = this.Tr.delete(e), this.dr = this.dr.delete(e);\n }\n yr(e) {\n const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1);\n let i = __PRIVATE_documentKeySet();\n return this.dr.forEachInRange([ n, r ], (e => {\n i = i.add(e.key);\n })), i;\n }\n containsKey(e) {\n const t = new __PRIVATE_DocReference(e, 0), n = this.Tr.firstAfterOrEqual(t);\n return null !== n && e.isEqual(n.key);\n }\n}\n\nclass __PRIVATE_DocReference {\n constructor(e, t) {\n this.key = e, this.wr = t;\n }\n /** Compare by key then by ID */ static Er(e, t) {\n return DocumentKey.comparator(e.key, t.key) || __PRIVATE_primitiveComparator(e.wr, t.wr);\n }\n /** Compare by ID then by key */ static Ar(e, t) {\n return __PRIVATE_primitiveComparator(e.wr, t.wr) || DocumentKey.comparator(e.key, t.key);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryMutationQueue {\n constructor(e, t) {\n this.indexManager = e, this.referenceDelegate = t, \n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n this.mutationQueue = [], \n /** Next value to use when assigning sequential IDs to each mutation batch. */\n this.Sr = 1, \n /** An ordered mapping between documents and the mutations batch IDs. */\n this.br = new SortedSet(__PRIVATE_DocReference.Er);\n }\n checkEmpty(e) {\n return PersistencePromise.resolve(0 === this.mutationQueue.length);\n }\n addMutationBatch(e, t, n, r) {\n const i = this.Sr;\n this.Sr++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];\n const s = new MutationBatch(i, t, n, r);\n this.mutationQueue.push(s);\n // Track references by document key and index collection parents.\n for (const t of r) this.br = this.br.add(new __PRIVATE_DocReference(t.key, i)), \n this.indexManager.addToCollectionParentIndex(e, t.key.path.popLast());\n return PersistencePromise.resolve(s);\n }\n lookupMutationBatch(e, t) {\n return PersistencePromise.resolve(this.Dr(t));\n }\n getNextMutationBatchAfterBatchId(e, t) {\n const n = t + 1, r = this.vr(n), i = r < 0 ? 0 : r;\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n return PersistencePromise.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);\n }\n getHighestUnacknowledgedBatchId() {\n return PersistencePromise.resolve(0 === this.mutationQueue.length ? -1 : this.Sr - 1);\n }\n getAllMutationBatches(e) {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n getAllMutationBatchesAffectingDocumentKey(e, t) {\n const n = new __PRIVATE_DocReference(t, 0), r = new __PRIVATE_DocReference(t, Number.POSITIVE_INFINITY), i = [];\n return this.br.forEachInRange([ n, r ], (e => {\n const t = this.Dr(e.wr);\n i.push(t);\n })), PersistencePromise.resolve(i);\n }\n getAllMutationBatchesAffectingDocumentKeys(e, t) {\n let n = new SortedSet(__PRIVATE_primitiveComparator);\n return t.forEach((e => {\n const t = new __PRIVATE_DocReference(e, 0), r = new __PRIVATE_DocReference(e, Number.POSITIVE_INFINITY);\n this.br.forEachInRange([ t, r ], (e => {\n n = n.add(e.wr);\n }));\n })), PersistencePromise.resolve(this.Cr(n));\n }\n getAllMutationBatchesAffectingQuery(e, t) {\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const n = t.path, r = n.length + 1;\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let i = n;\n DocumentKey.isDocumentKey(i) || (i = i.child(\"\"));\n const s = new __PRIVATE_DocReference(new DocumentKey(i), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let o = new SortedSet(__PRIVATE_primitiveComparator);\n return this.br.forEachWhile((e => {\n const t = e.key.path;\n return !!n.isPrefixOf(t) && (\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n t.length === r && (o = o.add(e.wr)), !0);\n }), s), PersistencePromise.resolve(this.Cr(o));\n }\n Cr(e) {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const t = [];\n return e.forEach((e => {\n const n = this.Dr(e);\n null !== n && t.push(n);\n })), t;\n }\n removeMutationBatch(e, t) {\n __PRIVATE_hardAssert(0 === this.Fr(t.batchId, \"removed\")), this.mutationQueue.shift();\n let n = this.br;\n return PersistencePromise.forEach(t.mutations, (r => {\n const i = new __PRIVATE_DocReference(r.key, t.batchId);\n return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(e, r.key);\n })).next((() => {\n this.br = n;\n }));\n }\n On(e) {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n containsKey(e, t) {\n const n = new __PRIVATE_DocReference(t, 0), r = this.br.firstAfterOrEqual(n);\n return PersistencePromise.resolve(t.isEqual(r && r.key));\n }\n performConsistencyCheck(e) {\n return this.mutationQueue.length, PersistencePromise.resolve();\n }\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */ Fr(e, t) {\n return this.vr(e);\n }\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been removed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */ vr(e) {\n if (0 === this.mutationQueue.length) \n // As an index this is past the end of the queue\n return 0;\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n return e - this.mutationQueue[0].batchId;\n }\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficient.\n */ Dr(e) {\n const t = this.vr(e);\n if (t < 0 || t >= this.mutationQueue.length) return null;\n return this.mutationQueue[t];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass __PRIVATE_MemoryRemoteDocumentCacheImpl {\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(e) {\n this.Mr = e, \n /** Underlying cache of documents and their read times. */\n this.docs = function __PRIVATE_documentEntryMap() {\n return new SortedMap(DocumentKey.comparator);\n }(), \n /** Size of all cached documents. */\n this.size = 0;\n }\n setIndexManager(e) {\n this.indexManager = e;\n }\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ addEntry(e, t) {\n const n = t.key, r = this.docs.get(n), i = r ? r.size : 0, s = this.Mr(t);\n return this.docs = this.docs.insert(n, {\n document: t.mutableCopy(),\n size: s\n }), this.size += s - i, this.indexManager.addToCollectionParentIndex(e, n.path.popLast());\n }\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ removeEntry(e) {\n const t = this.docs.get(e);\n t && (this.docs = this.docs.remove(e), this.size -= t.size);\n }\n getEntry(e, t) {\n const n = this.docs.get(t);\n return PersistencePromise.resolve(n ? n.document.mutableCopy() : MutableDocument.newInvalidDocument(t));\n }\n getEntries(e, t) {\n let n = __PRIVATE_mutableDocumentMap();\n return t.forEach((e => {\n const t = this.docs.get(e);\n n = n.insert(e, t ? t.document.mutableCopy() : MutableDocument.newInvalidDocument(e));\n })), PersistencePromise.resolve(n);\n }\n getDocumentsMatchingQuery(e, t, n, r) {\n let i = __PRIVATE_mutableDocumentMap();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const s = t.path, o = new DocumentKey(s.child(\"\")), _ = this.docs.getIteratorFrom(o);\n for (;_.hasNext(); ) {\n const {key: e, value: {document: o}} = _.getNext();\n if (!s.isPrefixOf(e.path)) break;\n e.path.length > s.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(o), n) <= 0 || (r.has(o.key) || __PRIVATE_queryMatches(t, o)) && (i = i.insert(o.key, o.mutableCopy())));\n }\n return PersistencePromise.resolve(i);\n }\n getAllFromCollectionGroup(e, t, n, r) {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n fail();\n }\n Or(e, t) {\n return PersistencePromise.forEach(this.docs, (e => t(e)));\n }\n newChangeBuffer(e) {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this);\n }\n getSize(e) {\n return PersistencePromise.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n constructor(e) {\n super(), this.cr = e;\n }\n applyChanges(e) {\n const t = [];\n return this.changes.forEach(((n, r) => {\n r.isValidDocument() ? t.push(this.cr.addEntry(e, r)) : this.cr.removeEntry(n);\n })), PersistencePromise.waitFor(t);\n }\n getFromCache(e, t) {\n return this.cr.getEntry(e, t);\n }\n getAllFromCache(e, t) {\n return this.cr.getEntries(e, t);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryTargetCache {\n constructor(e) {\n this.persistence = e, \n /**\n * Maps a target to the data about that target\n */\n this.Nr = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), \n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = SnapshotVersion.min(), \n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0, \n /** The highest sequence number encountered. */\n this.Lr = 0, \n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.Br = new __PRIVATE_ReferenceSet, this.targetCount = 0, this.kr = __PRIVATE_TargetIdGenerator.Bn();\n }\n forEachTarget(e, t) {\n return this.Nr.forEach(((e, n) => t(n))), PersistencePromise.resolve();\n }\n getLastRemoteSnapshotVersion(e) {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n getHighestSequenceNumber(e) {\n return PersistencePromise.resolve(this.Lr);\n }\n allocateTargetId(e) {\n return this.highestTargetId = this.kr.next(), PersistencePromise.resolve(this.highestTargetId);\n }\n setTargetsMetadata(e, t, n) {\n return n && (this.lastRemoteSnapshotVersion = n), t > this.Lr && (this.Lr = t), \n PersistencePromise.resolve();\n }\n Kn(e) {\n this.Nr.set(e.target, e);\n const t = e.targetId;\n t > this.highestTargetId && (this.kr = new __PRIVATE_TargetIdGenerator(t), this.highestTargetId = t), \n e.sequenceNumber > this.Lr && (this.Lr = e.sequenceNumber);\n }\n addTargetData(e, t) {\n return this.Kn(t), this.targetCount += 1, PersistencePromise.resolve();\n }\n updateTargetData(e, t) {\n return this.Kn(t), PersistencePromise.resolve();\n }\n removeTargetData(e, t) {\n return this.Nr.delete(t.target), this.Br.gr(t.targetId), this.targetCount -= 1, \n PersistencePromise.resolve();\n }\n removeTargets(e, t, n) {\n let r = 0;\n const i = [];\n return this.Nr.forEach(((s, o) => {\n o.sequenceNumber <= t && null === n.get(o.targetId) && (this.Nr.delete(s), i.push(this.removeMatchingKeysForTargetId(e, o.targetId)), \n r++);\n })), PersistencePromise.waitFor(i).next((() => r));\n }\n getTargetCount(e) {\n return PersistencePromise.resolve(this.targetCount);\n }\n getTargetData(e, t) {\n const n = this.Nr.get(t) || null;\n return PersistencePromise.resolve(n);\n }\n addMatchingKeys(e, t, n) {\n return this.Br.Rr(t, n), PersistencePromise.resolve();\n }\n removeMatchingKeys(e, t, n) {\n this.Br.mr(t, n);\n const r = this.persistence.referenceDelegate, i = [];\n return r && t.forEach((t => {\n i.push(r.markPotentiallyOrphaned(e, t));\n })), PersistencePromise.waitFor(i);\n }\n removeMatchingKeysForTargetId(e, t) {\n return this.Br.gr(t), PersistencePromise.resolve();\n }\n getMatchingKeysForTargetId(e, t) {\n const n = this.Br.yr(t);\n return PersistencePromise.resolve(n);\n }\n containsKey(e, t) {\n return PersistencePromise.resolve(this.Br.containsKey(t));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nclass __PRIVATE_MemoryPersistence {\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(e, t) {\n this.qr = {}, this.overlays = {}, this.Qr = new __PRIVATE_ListenSequence(0), this.Kr = !1, \n this.Kr = !0, this.$r = new __PRIVATE_MemoryGlobalsCache, this.referenceDelegate = e(this), \n this.Ur = new __PRIVATE_MemoryTargetCache(this);\n this.indexManager = new __PRIVATE_MemoryIndexManager, this.remoteDocumentCache = function __PRIVATE_newMemoryRemoteDocumentCache(e) {\n return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e);\n }((e => this.referenceDelegate.Wr(e))), this.serializer = new __PRIVATE_LocalSerializer(t), \n this.Gr = new __PRIVATE_MemoryBundleCache(this.serializer);\n }\n start() {\n return Promise.resolve();\n }\n shutdown() {\n // No durable state to ensure is closed on shutdown.\n return this.Kr = !1, Promise.resolve();\n }\n get started() {\n return this.Kr;\n }\n setDatabaseDeletedListener() {\n // No op.\n }\n setNetworkEnabled() {\n // No op.\n }\n getIndexManager(e) {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n getDocumentOverlayCache(e) {\n let t = this.overlays[e.toKey()];\n return t || (t = new __PRIVATE_MemoryDocumentOverlayCache, this.overlays[e.toKey()] = t), \n t;\n }\n getMutationQueue(e, t) {\n let n = this.qr[e.toKey()];\n return n || (n = new __PRIVATE_MemoryMutationQueue(t, this.referenceDelegate), this.qr[e.toKey()] = n), \n n;\n }\n getGlobalsCache() {\n return this.$r;\n }\n getTargetCache() {\n return this.Ur;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getBundleCache() {\n return this.Gr;\n }\n runTransaction(e, t, n) {\n __PRIVATE_logDebug(\"MemoryPersistence\", \"Starting transaction:\", e);\n const r = new __PRIVATE_MemoryTransaction(this.Qr.next());\n return this.referenceDelegate.zr(), n(r).next((e => this.referenceDelegate.jr(r).next((() => e)))).toPromise().then((e => (r.raiseOnCommittedEvent(), \n e)));\n }\n Hr(e, t) {\n return PersistencePromise.or(Object.values(this.qr).map((n => () => n.containsKey(e, t))));\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */ class __PRIVATE_MemoryTransaction extends PersistenceTransaction {\n constructor(e) {\n super(), this.currentSequenceNumber = e;\n }\n}\n\nclass __PRIVATE_MemoryEagerDelegate {\n constructor(e) {\n this.persistence = e, \n /** Tracks all documents that are active in Query views. */\n this.Jr = new __PRIVATE_ReferenceSet, \n /** The list of documents that are potentially GCed after each transaction. */\n this.Yr = null;\n }\n static Zr(e) {\n return new __PRIVATE_MemoryEagerDelegate(e);\n }\n get Xr() {\n if (this.Yr) return this.Yr;\n throw fail();\n }\n addReference(e, t, n) {\n return this.Jr.addReference(n, t), this.Xr.delete(n.toString()), PersistencePromise.resolve();\n }\n removeReference(e, t, n) {\n return this.Jr.removeReference(n, t), this.Xr.add(n.toString()), PersistencePromise.resolve();\n }\n markPotentiallyOrphaned(e, t) {\n return this.Xr.add(t.toString()), PersistencePromise.resolve();\n }\n removeTarget(e, t) {\n this.Jr.gr(t.targetId).forEach((e => this.Xr.add(e.toString())));\n const n = this.persistence.getTargetCache();\n return n.getMatchingKeysForTargetId(e, t.targetId).next((e => {\n e.forEach((e => this.Xr.add(e.toString())));\n })).next((() => n.removeTargetData(e, t)));\n }\n zr() {\n this.Yr = new Set;\n }\n jr(e) {\n // Remove newly orphaned documents.\n const t = this.persistence.getRemoteDocumentCache().newChangeBuffer();\n return PersistencePromise.forEach(this.Xr, (n => {\n const r = DocumentKey.fromPath(n);\n return this.ei(e, r).next((e => {\n e || t.removeEntry(r, SnapshotVersion.min());\n }));\n })).next((() => (this.Yr = null, t.apply(e))));\n }\n updateLimboDocument(e, t) {\n return this.ei(e, t).next((e => {\n e ? this.Xr.delete(t.toString()) : this.Xr.add(t.toString());\n }));\n }\n Wr(e) {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n ei(e, t) {\n return PersistencePromise.or([ () => PersistencePromise.resolve(this.Jr.containsKey(t)), () => this.persistence.getTargetCache().containsKey(e, t), () => this.persistence.Hr(e, t) ]);\n }\n}\n\nclass __PRIVATE_MemoryLruDelegate {\n constructor(e, t) {\n this.persistence = e, this.ti = new ObjectMap((e => __PRIVATE_encodeResourcePath(e.path)), ((e, t) => e.isEqual(t))), \n this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);\n }\n static Zr(e, t) {\n return new __PRIVATE_MemoryLruDelegate(e, t);\n }\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n zr() {}\n jr(e) {\n return PersistencePromise.resolve();\n }\n forEachTarget(e, t) {\n return this.persistence.getTargetCache().forEachTarget(e, t);\n }\n Yn(e) {\n const t = this.er(e);\n return this.persistence.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t))));\n }\n er(e) {\n let t = 0;\n return this.Zn(e, (e => {\n t++;\n })).next((() => t));\n }\n Zn(e, t) {\n return PersistencePromise.forEach(this.ti, ((n, r) => this.nr(e, n, r).next((e => e ? PersistencePromise.resolve() : t(r)))));\n }\n removeTargets(e, t, n) {\n return this.persistence.getTargetCache().removeTargets(e, t, n);\n }\n removeOrphanedDocuments(e, t) {\n let n = 0;\n const r = this.persistence.getRemoteDocumentCache(), i = r.newChangeBuffer();\n return r.Or(e, (r => this.nr(e, r, t).next((e => {\n e || (n++, i.removeEntry(r, SnapshotVersion.min()));\n })))).next((() => i.apply(e))).next((() => n));\n }\n markPotentiallyOrphaned(e, t) {\n return this.ti.set(t, e.currentSequenceNumber), PersistencePromise.resolve();\n }\n removeTarget(e, t) {\n const n = t.withSequenceNumber(e.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(e, n);\n }\n addReference(e, t, n) {\n return this.ti.set(n, e.currentSequenceNumber), PersistencePromise.resolve();\n }\n removeReference(e, t, n) {\n return this.ti.set(n, e.currentSequenceNumber), PersistencePromise.resolve();\n }\n updateLimboDocument(e, t) {\n return this.ti.set(t, e.currentSequenceNumber), PersistencePromise.resolve();\n }\n Wr(e) {\n let t = e.key.toString().length;\n return e.isFoundDocument() && (t += __PRIVATE_estimateByteSize(e.data.value)), t;\n }\n nr(e, t, n) {\n return PersistencePromise.or([ () => this.persistence.Hr(e, t), () => this.persistence.getTargetCache().containsKey(e, t), () => {\n const e = this.ti.get(t);\n return PersistencePromise.resolve(void 0 !== e && e > n);\n } ]);\n }\n getCacheSize(e) {\n return this.persistence.getRemoteDocumentCache().getSize(e);\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/** Performs database creation and schema upgrades. */ class __PRIVATE_SchemaConverter {\n constructor(e) {\n this.serializer = e;\n }\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */ O(e, t, n, r) {\n const i = new __PRIVATE_SimpleDbTransaction(\"createOrUpgrade\", t);\n n < 1 && r >= 1 && (!function __PRIVATE_createPrimaryClientStore(e) {\n e.createObjectStore(\"owner\");\n }(e), function __PRIVATE_createMutationQueue(e) {\n e.createObjectStore(\"mutationQueues\", {\n keyPath: \"userId\"\n });\n e.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", M, {\n unique: !0\n }), e.createObjectStore(\"documentMutations\");\n }\n /**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */ (e), __PRIVATE_createQueryCache(e), function __PRIVATE_createLegacyRemoteDocumentCache(e) {\n e.createObjectStore(\"remoteDocuments\");\n }(e));\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n let s = PersistencePromise.resolve();\n return n < 3 && r >= 3 && (\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n 0 !== n && (!function __PRIVATE_dropQueryCache(e) {\n e.deleteObjectStore(\"targetDocuments\"), e.deleteObjectStore(\"targets\"), e.deleteObjectStore(\"targetGlobal\");\n }(e), __PRIVATE_createQueryCache(e)), s = s.next((() => \n /**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\n function __PRIVATE_writeEmptyTargetGlobalEntry(e) {\n const t = e.store(\"targetGlobal\"), n = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return t.put(\"targetGlobalKey\", n);\n }(i)))), n < 4 && r >= 4 && (0 !== n && (\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n s = s.next((() => function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e, t) {\n return t.store(\"mutations\").U().next((n => {\n e.deleteObjectStore(\"mutations\");\n e.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", M, {\n unique: !0\n });\n const r = t.store(\"mutations\"), i = n.map((e => r.put(e)));\n return PersistencePromise.waitFor(i);\n }));\n }(e, i)))), s = s.next((() => {\n !function __PRIVATE_createClientMetadataStore(e) {\n e.createObjectStore(\"clientMetadata\", {\n keyPath: \"clientId\"\n });\n }(e);\n }))), n < 5 && r >= 5 && (s = s.next((() => this.ni(i)))), n < 6 && r >= 6 && (s = s.next((() => (function __PRIVATE_createDocumentGlobalStore(e) {\n e.createObjectStore(\"remoteDocumentGlobal\");\n }(e), this.ri(i))))), n < 7 && r >= 7 && (s = s.next((() => this.ii(i)))), n < 8 && r >= 8 && (s = s.next((() => this.si(e, i)))), \n n < 9 && r >= 9 && (s = s.next((() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n !function __PRIVATE_dropRemoteDocumentChangesStore(e) {\n e.objectStoreNames.contains(\"remoteDocumentChanges\") && e.deleteObjectStore(\"remoteDocumentChanges\");\n }(e);\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n }))), n < 10 && r >= 10 && (s = s.next((() => this.oi(i)))), n < 11 && r >= 11 && (s = s.next((() => {\n !function __PRIVATE_createBundlesStore(e) {\n e.createObjectStore(\"bundles\", {\n keyPath: \"bundleId\"\n });\n }(e), function __PRIVATE_createNamedQueriesStore(e) {\n e.createObjectStore(\"namedQueries\", {\n keyPath: \"name\"\n });\n }(e);\n }))), n < 12 && r >= 12 && (s = s.next((() => {\n !function __PRIVATE_createDocumentOverlayStore(e) {\n const t = e.createObjectStore(\"documentOverlays\", {\n keyPath: G\n });\n t.createIndex(\"collectionPathOverlayIndex\", z, {\n unique: !1\n }), t.createIndex(\"collectionGroupOverlayIndex\", j, {\n unique: !1\n });\n }(e);\n }))), n < 13 && r >= 13 && (s = s.next((() => function __PRIVATE_createRemoteDocumentCache(e) {\n const t = e.createObjectStore(\"remoteDocumentsV14\", {\n keyPath: O\n });\n t.createIndex(\"documentKeyIndex\", N), t.createIndex(\"collectionGroupIndex\", L);\n }(e))).next((() => this._i(e, i))).next((() => e.deleteObjectStore(\"remoteDocuments\")))), \n n < 14 && r >= 14 && (s = s.next((() => this.ai(e, i)))), n < 15 && r >= 15 && (s = s.next((() => function __PRIVATE_createFieldIndex(e) {\n e.createObjectStore(\"indexConfiguration\", {\n keyPath: \"indexId\",\n autoIncrement: !0\n }).createIndex(\"collectionGroupIndex\", \"collectionGroup\", {\n unique: !1\n });\n e.createObjectStore(\"indexState\", {\n keyPath: K\n }).createIndex(\"sequenceNumberIndex\", $, {\n unique: !1\n });\n e.createObjectStore(\"indexEntries\", {\n keyPath: U\n }).createIndex(\"documentKeyIndex\", W, {\n unique: !1\n });\n }(e)))), n < 16 && r >= 16 && (\n // Clear the object stores to remove possibly corrupted index entries\n s = s.next((() => {\n t.objectStore(\"indexState\").clear();\n })).next((() => {\n t.objectStore(\"indexEntries\").clear();\n }))), n < 17 && r >= 17 && (s = s.next((() => {\n !function __PRIVATE_createGlobalsStore(e) {\n e.createObjectStore(\"globals\", {\n keyPath: \"name\"\n });\n }(e);\n }))), s;\n }\n ri(e) {\n let t = 0;\n return e.store(\"remoteDocuments\").J(((e, n) => {\n t += __PRIVATE_dbDocumentSize(n);\n })).next((() => {\n const n = {\n byteSize: t\n };\n return e.store(\"remoteDocumentGlobal\").put(\"remoteDocumentGlobalKey\", n);\n }));\n }\n ni(e) {\n const t = e.store(\"mutationQueues\"), n = e.store(\"mutations\");\n return t.U().next((t => PersistencePromise.forEach(t, (t => {\n const r = IDBKeyRange.bound([ t.userId, -1 ], [ t.userId, t.lastAcknowledgedBatchId ]);\n return n.U(\"userMutationsIndex\", r).next((n => PersistencePromise.forEach(n, (n => {\n __PRIVATE_hardAssert(n.userId === t.userId);\n const r = __PRIVATE_fromDbMutationBatch(this.serializer, n);\n return removeMutationBatch(e, t.userId, r).next((() => {}));\n }))));\n }))));\n }\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */ ii(e) {\n const t = e.store(\"targetDocuments\"), n = e.store(\"remoteDocuments\");\n return e.store(\"targetGlobal\").get(\"targetGlobalKey\").next((e => {\n const r = [];\n return n.J(((n, i) => {\n const s = new ResourcePath(n), o = function __PRIVATE_sentinelKey(e) {\n return [ 0, __PRIVATE_encodeResourcePath(e) ];\n }(s);\n r.push(t.get(o).next((n => n ? PersistencePromise.resolve() : (n => t.put({\n targetId: 0,\n path: __PRIVATE_encodeResourcePath(n),\n sequenceNumber: e.highestListenSequenceNumber\n }))(s))));\n })).next((() => PersistencePromise.waitFor(r)));\n }));\n }\n si(e, t) {\n // Create the index.\n e.createObjectStore(\"collectionParents\", {\n keyPath: Q\n });\n const n = t.store(\"collectionParents\"), r = new __PRIVATE_MemoryCollectionParentIndex, addEntry = e => {\n if (r.add(e)) {\n const t = e.lastSegment(), r = e.popLast();\n return n.put({\n collectionId: t,\n parent: __PRIVATE_encodeResourcePath(r)\n });\n }\n };\n // Helper to add an index entry iff we haven't already written it.\n // Index existing remote documents.\n return t.store(\"remoteDocuments\").J({\n H: !0\n }, ((e, t) => {\n const n = new ResourcePath(e);\n return addEntry(n.popLast());\n })).next((() => t.store(\"documentMutations\").J({\n H: !0\n }, (([e, t, n], r) => {\n const i = __PRIVATE_decodeResourcePath(t);\n return addEntry(i.popLast());\n }))));\n }\n oi(e) {\n const t = e.store(\"targets\");\n return t.J(((e, n) => {\n const r = __PRIVATE_fromDbTarget(n), i = __PRIVATE_toDbTarget(this.serializer, r);\n return t.put(i);\n }));\n }\n _i(e, t) {\n const n = t.store(\"remoteDocuments\"), r = [];\n return n.J(((e, n) => {\n const i = t.store(\"remoteDocumentsV14\"), s = function __PRIVATE_extractKey(e) {\n return e.document ? new DocumentKey(ResourcePath.fromString(e.document.name).popFirst(5)) : e.noDocument ? DocumentKey.fromSegments(e.noDocument.path) : e.unknownDocument ? DocumentKey.fromSegments(e.unknownDocument.path) : fail();\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n).path.toArray(), o = {\n prefixPath: s.slice(0, s.length - 2),\n collectionGroup: s[s.length - 2],\n documentId: s[s.length - 1],\n readTime: n.readTime || [ 0, 0 ],\n unknownDocument: n.unknownDocument,\n noDocument: n.noDocument,\n document: n.document,\n hasCommittedMutations: !!n.hasCommittedMutations\n };\n r.push(i.put(o));\n })).next((() => PersistencePromise.waitFor(r)));\n }\n ai(e, t) {\n const n = t.store(\"mutations\"), r = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Zr, this.serializer.ct);\n return n.U().next((e => {\n const n = new Map;\n return e.forEach((e => {\n var t;\n let r = null !== (t = n.get(e.userId)) && void 0 !== t ? t : __PRIVATE_documentKeySet();\n __PRIVATE_fromDbMutationBatch(this.serializer, e).keys().forEach((e => r = r.add(e))), \n n.set(e.userId, r);\n })), PersistencePromise.forEach(n, ((e, n) => {\n const s = new User(n), o = __PRIVATE_IndexedDbDocumentOverlayCache.lt(this.serializer, s), _ = i.getIndexManager(s), a = __PRIVATE_IndexedDbMutationQueue.lt(s, this.serializer, _, i.referenceDelegate);\n return new LocalDocumentsView(r, a, o, _).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t, __PRIVATE_ListenSequence.oe), e).next();\n }));\n }));\n }\n}\n\nfunction __PRIVATE_createQueryCache(e) {\n e.createObjectStore(\"targetDocuments\", {\n keyPath: k\n }).createIndex(\"documentTargetsIndex\", q, {\n unique: !0\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n e.createObjectStore(\"targets\", {\n keyPath: \"targetId\"\n }).createIndex(\"queryTargetsIndex\", B, {\n unique: !0\n }), e.createObjectStore(\"targetGlobal\");\n}\n\nconst Ve = \"Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.\";\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nclass __PRIVATE_IndexedDbPersistence {\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n e, t, n, r, i, s, o, _, a, \n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n u, c = 17) {\n if (this.allowTabSynchronization = e, this.persistenceKey = t, this.clientId = n, \n this.ui = i, this.window = s, this.document = o, this.ci = a, this.li = u, this.hi = c, \n this.Qr = null, this.Kr = !1, this.isPrimary = !1, this.networkEnabled = !0, \n /** Our window.unload handler, if registered. */\n this.Pi = null, this.inForeground = !1, \n /** Our 'visibilitychange' listener if registered. */\n this.Ii = null, \n /** The client metadata refresh task. */\n this.Ti = null, \n /** The last time we garbage collected the client metadata object store. */\n this.Ei = Number.NEGATIVE_INFINITY, \n /** A listener to notify on primary state changes. */\n this.di = e => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.D()) throw new FirestoreError(D.UNIMPLEMENTED, \"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.\");\n this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r), this.Ai = t + \"main\", \n this.serializer = new __PRIVATE_LocalSerializer(_), this.Ri = new __PRIVATE_SimpleDb(this.Ai, this.hi, new __PRIVATE_SchemaConverter(this.serializer)), \n this.$r = new __PRIVATE_IndexedDbGlobalsCache, this.Ur = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), \n this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), \n this.Gr = new __PRIVATE_IndexedDbBundleCache, this.window && this.window.localStorage ? this.Vi = this.window.localStorage : (this.Vi = null, \n !1 === u && __PRIVATE_logError(\"IndexedDbPersistence\", \"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.\"));\n }\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */ start() {\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.mi().then((() => {\n if (!this.isPrimary && !this.allowTabSynchronization) \n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(D.FAILED_PRECONDITION, Ve);\n return this.fi(), this.gi(), this.pi(), this.runTransaction(\"getHighestListenSequenceNumber\", \"readonly\", (e => this.Ur.getHighestSequenceNumber(e)));\n })).then((e => {\n this.Qr = new __PRIVATE_ListenSequence(e, this.ci);\n })).then((() => {\n this.Kr = !0;\n })).catch((e => (this.Ri && this.Ri.close(), Promise.reject(e))));\n }\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ yi(e) {\n return this.di = async t => {\n if (this.started) return e(t);\n }, e(this.isPrimary);\n }\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setDatabaseDeletedListener(e) {\n this.Ri.L((async t => {\n // Check if an attempt is made to delete IndexedDB.\n null === t.newVersion && await e();\n }));\n }\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setNetworkEnabled(e) {\n this.networkEnabled !== e && (this.networkEnabled = e, \n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.ui.enqueueAndForget((async () => {\n this.started && await this.mi();\n })));\n }\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */ mi() {\n return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\", \"readwrite\", (e => __PRIVATE_clientMetadataStore(e).put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n }).next((() => {\n if (this.isPrimary) return this.wi(e).next((e => {\n e || (this.isPrimary = !1, this.ui.enqueueRetryable((() => this.di(!1))));\n }));\n })).next((() => this.Si(e))).next((t => this.isPrimary && !t ? this.bi(e).next((() => !1)) : !!t && this.Di(e).next((() => !0)))))).catch((e => {\n if (__PRIVATE_isIndexedDbTransactionError(e)) \n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Failed to extend owner lease: \", e), \n this.isPrimary;\n if (!this.allowTabSynchronization) throw e;\n return __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Releasing owner lease after error during lease refresh\", e), \n /* isPrimary= */ !1;\n })).then((e => {\n this.isPrimary !== e && this.ui.enqueueRetryable((() => this.di(e))), this.isPrimary = e;\n }));\n }\n wi(e) {\n return __PRIVATE_primaryClientStore(e).get(\"owner\").next((e => PersistencePromise.resolve(this.vi(e))));\n }\n Ci(e) {\n return __PRIVATE_clientMetadataStore(e).delete(this.clientId);\n }\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */ async Fi() {\n if (this.isPrimary && !this.Mi(this.Ei, 18e5)) {\n this.Ei = Date.now();\n const e = await this.runTransaction(\"maybeGarbageCollectMultiClientState\", \"readwrite-primary\", (e => {\n const t = __PRIVATE_getStore(e, \"clientMetadata\");\n return t.U().next((e => {\n const n = this.xi(e, 18e5), r = e.filter((e => -1 === n.indexOf(e)));\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(r, (e => t.delete(e.clientId))).next((() => r));\n }));\n })).catch((() => []));\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.Vi) for (const t of e) this.Vi.removeItem(this.Oi(t.clientId));\n }\n }\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */ pi() {\n this.Ti = this.ui.enqueueAfterDelay(\"client_metadata_refresh\" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.mi().then((() => this.Fi())).then((() => this.pi()))));\n }\n /** Checks whether `client` is the local client. */ vi(e) {\n return !!e && e.ownerId === this.clientId;\n }\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */ Si(e) {\n if (this.li) return PersistencePromise.resolve(!0);\n return __PRIVATE_primaryClientStore(e).get(\"owner\").next((t => {\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (null !== t && this.Mi(t.leaseTimestampMs, 5e3) && !this.Ni(t.ownerId)) {\n if (this.vi(t) && this.networkEnabled) return !0;\n if (!this.vi(t)) {\n if (!t.allowTabSynchronization) \n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(D.FAILED_PRECONDITION, Ve);\n return !1;\n }\n }\n return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e).U().next((e => void 0 === this.xi(e, 5e3).find((e => {\n if (this.clientId !== e.clientId) {\n const t = !this.networkEnabled && e.networkEnabled, n = !this.inForeground && e.inForeground, r = this.networkEnabled === e.networkEnabled;\n if (t || n && r) return !0;\n }\n return !1;\n }))));\n })).next((e => (this.isPrimary !== e && __PRIVATE_logDebug(\"IndexedDbPersistence\", `Client ${e ? \"is\" : \"is not\"} eligible for a primary lease.`), \n e)));\n }\n async shutdown() {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this.Kr = !1, this.Li(), this.Ti && (this.Ti.cancel(), this.Ti = null), this.Bi(), \n this.ki(), \n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.Ri.runTransaction(\"shutdown\", \"readwrite\", [ \"owner\", \"clientMetadata\" ], (e => {\n const t = new __PRIVATE_IndexedDbTransaction(e, __PRIVATE_ListenSequence.oe);\n return this.bi(t).next((() => this.Ci(t)));\n })), this.Ri.close(), \n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.qi();\n }\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */ xi(e, t) {\n return e.filter((e => this.Mi(e.updateTimeMs, t) && !this.Ni(e.clientId)));\n }\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ Qi() {\n return this.runTransaction(\"getActiveClients\", \"readonly\", (e => __PRIVATE_clientMetadataStore(e).U().next((e => this.xi(e, 18e5).map((e => e.clientId))))));\n }\n get started() {\n return this.Kr;\n }\n getGlobalsCache() {\n return this.$r;\n }\n getMutationQueue(e, t) {\n return __PRIVATE_IndexedDbMutationQueue.lt(e, this.serializer, t, this.referenceDelegate);\n }\n getTargetCache() {\n return this.Ur;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getIndexManager(e) {\n return new __PRIVATE_IndexedDbIndexManager(e, this.serializer.ct.databaseId);\n }\n getDocumentOverlayCache(e) {\n return __PRIVATE_IndexedDbDocumentOverlayCache.lt(this.serializer, e);\n }\n getBundleCache() {\n return this.Gr;\n }\n runTransaction(e, t, n) {\n __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Starting transaction:\", e);\n const r = \"readonly\" === t ? \"readonly\" : \"readwrite\", i = \n /** Returns the object stores for the provided schema. */\n function __PRIVATE_getObjectStores(e) {\n return 17 === e ? te : 16 === e ? ee : 15 === e ? X : 14 === e ? Z : 13 === e ? Y : 12 === e ? J : 11 === e ? H : void fail();\n }(this.hi);\n let s;\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.Ri.runTransaction(e, r, i, (r => (s = new __PRIVATE_IndexedDbTransaction(r, this.Qr ? this.Qr.next() : __PRIVATE_ListenSequence.oe), \n \"readwrite-primary\" === t ? this.wi(s).next((e => !!e || this.Si(s))).next((t => {\n if (!t) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`), \n this.isPrimary = !1, this.ui.enqueueRetryable((() => this.di(!1))), new FirestoreError(D.FAILED_PRECONDITION, C);\n return n(s);\n })).next((e => this.Di(s).next((() => e)))) : this.Ki(s).next((() => n(s)))))).then((e => (s.raiseOnCommittedEvent(), \n e)));\n }\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n Ki(e) {\n return __PRIVATE_primaryClientStore(e).get(\"owner\").next((e => {\n if (null !== e && this.Mi(e.leaseTimestampMs, 5e3) && !this.Ni(e.ownerId) && !this.vi(e) && !(this.li || this.allowTabSynchronization && e.allowTabSynchronization)) throw new FirestoreError(D.FAILED_PRECONDITION, Ve);\n }));\n }\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */ Di(e) {\n const t = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return __PRIVATE_primaryClientStore(e).put(\"owner\", t);\n }\n static D() {\n return __PRIVATE_SimpleDb.D();\n }\n /** Checks the primary lease and removes it if we are the current primary. */ bi(e) {\n const t = __PRIVATE_primaryClientStore(e);\n return t.get(\"owner\").next((e => this.vi(e) ? (__PRIVATE_logDebug(\"IndexedDbPersistence\", \"Releasing primary lease.\"), \n t.delete(\"owner\")) : PersistencePromise.resolve()));\n }\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ Mi(e, t) {\n const n = Date.now();\n return !(e < n - t) && (!(e > n) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${n}`), \n !1));\n }\n fi() {\n null !== this.document && \"function\" == typeof this.document.addEventListener && (this.Ii = () => {\n this.ui.enqueueAndForget((() => (this.inForeground = \"visible\" === this.document.visibilityState, \n this.mi())));\n }, this.document.addEventListener(\"visibilitychange\", this.Ii), this.inForeground = \"visible\" === this.document.visibilityState);\n }\n Bi() {\n this.Ii && (this.document.removeEventListener(\"visibilitychange\", this.Ii), this.Ii = null);\n }\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */ gi() {\n var e;\n \"function\" == typeof (null === (e = this.window) || void 0 === e ? void 0 : e.addEventListener) && (this.Pi = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.Li();\n const e = /(?:Version|Mobile)\\/1[456]/;\n isSafari() && (navigator.appVersion.match(e) || navigator.userAgent.match(e)) && \n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.ui.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.ui.enqueueAndForget((() => this.shutdown()));\n }, this.window.addEventListener(\"pagehide\", this.Pi));\n }\n ki() {\n this.Pi && (this.window.removeEventListener(\"pagehide\", this.Pi), this.Pi = null);\n }\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */ Ni(e) {\n var t;\n try {\n const n = null !== (null === (t = this.Vi) || void 0 === t ? void 0 : t.getItem(this.Oi(e)));\n return __PRIVATE_logDebug(\"IndexedDbPersistence\", `Client '${e}' ${n ? \"is\" : \"is not\"} zombied in LocalStorage`), \n n;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n return __PRIVATE_logError(\"IndexedDbPersistence\", \"Failed to get zombied client id.\", e), \n !1;\n }\n }\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */ Li() {\n if (this.Vi) try {\n this.Vi.setItem(this.Oi(this.clientId), String(Date.now()));\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n __PRIVATE_logError(\"Failed to set zombie client id.\", e);\n }\n }\n /** Removes the zombied client entry if it exists. */ qi() {\n if (this.Vi) try {\n this.Vi.removeItem(this.Oi(this.clientId));\n } catch (e) {\n // Ignore\n }\n }\n Oi(e) {\n return `firestore_zombie_${this.persistenceKey}_${e}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */ function __PRIVATE_primaryClientStore(e) {\n return __PRIVATE_getStore(e, \"owner\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */ function __PRIVATE_clientMetadataStore(e) {\n return __PRIVATE_getStore(e, \"clientMetadata\");\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */ function __PRIVATE_indexedDbStoragePrefix(e, t) {\n // Use two different prefix formats:\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let n = e.projectId;\n return e.isDefaultDatabase || (n += \".\" + e.database), \"firestore/\" + t + \"/\" + n + \"/\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nclass __PRIVATE_LocalViewChanges {\n constructor(e, t, n, r) {\n this.targetId = e, this.fromCache = t, this.$i = n, this.Ui = r;\n }\n static Wi(e, t) {\n let n = __PRIVATE_documentKeySet(), r = __PRIVATE_documentKeySet();\n for (const e of t.docChanges) switch (e.type) {\n case 0 /* ChangeType.Added */ :\n n = n.add(e.doc.key);\n break;\n\n case 1 /* ChangeType.Removed */ :\n r = r.add(e.doc.key);\n // do nothing\n }\n return new __PRIVATE_LocalViewChanges(e, t.fromCache, n, r);\n }\n}\n\n/**\n * @license\n * Copyright 2023 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 * A tracker to keep a record of important details during database local query\n * execution.\n */ class QueryContext {\n constructor() {\n /**\n * Counts the number of documents passed through during local query execution.\n */\n this._documentReadCount = 0;\n }\n get documentReadCount() {\n return this._documentReadCount;\n }\n incrementDocumentReadCount(e) {\n this._documentReadCount += e;\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */\nclass __PRIVATE_QueryEngine {\n constructor() {\n this.Gi = !1, this.zi = !1, \n /**\n * SDK only decides whether it should create index when collection size is\n * larger than this.\n */\n this.ji = 100, this.Hi = \n /**\n * This cost represents the evaluation result of\n * (([index, docKey] + [docKey, docContent]) per document in the result set)\n * / ([docKey, docContent] per documents in full collection scan) coming from\n * experiment [enter PR experiment URL here].\n */\n function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument() {\n // These values were derived from an experiment where several members of the\n // Firestore SDK team ran a performance test in various environments.\n // Googlers can see b/299284287 for details.\n return isSafari() ? 8 : __PRIVATE_getAndroidVersion(getUA()) > 0 ? 6 : 4;\n }();\n }\n /** Sets the document view to query against. */ initialize(e, t) {\n this.Ji = e, this.indexManager = t, this.Gi = !0;\n }\n /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(e, t, n, r) {\n // Stores the result from executing the query; using this object is more\n // convenient than passing the result between steps of the persistence\n // transaction and improves readability comparatively.\n const i = {\n result: null\n };\n return this.Yi(e, t).next((e => {\n i.result = e;\n })).next((() => {\n if (!i.result) return this.Zi(e, t, r, n).next((e => {\n i.result = e;\n }));\n })).next((() => {\n if (i.result) return;\n const n = new QueryContext;\n return this.Xi(e, t, n).next((r => {\n if (i.result = r, this.zi) return this.es(e, t, n, r.size);\n }));\n })).next((() => i.result));\n }\n es(e, t, n, r) {\n return n.documentReadCount < this.ji ? (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"SDK will not create cache indexes for query:\", __PRIVATE_stringifyQuery(t), \"since it only creates cache indexes for collection contains\", \"more than or equal to\", this.ji, \"documents\"), \n PersistencePromise.resolve()) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"Query:\", __PRIVATE_stringifyQuery(t), \"scans\", n.documentReadCount, \"local documents and returns\", r, \"documents as results.\"), \n n.documentReadCount > this.Hi * r ? (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"The SDK decides to create cache indexes for query:\", __PRIVATE_stringifyQuery(t), \"as using cache indexes may help improve performance.\"), \n this.indexManager.createTargetIndexes(e, __PRIVATE_queryToTarget(t))) : PersistencePromise.resolve());\n }\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */ Yi(e, t) {\n if (__PRIVATE_queryMatchesAllDocuments(t)) \n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve(null);\n let n = __PRIVATE_queryToTarget(t);\n return this.indexManager.getIndexType(e, n).next((r => 0 /* IndexType.NONE */ === r ? null : (null !== t.limit && 1 /* IndexType.PARTIAL */ === r && (\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n t = __PRIVATE_queryWithLimit(t, null, \"F\" /* LimitType.First */), n = __PRIVATE_queryToTarget(t)), \n this.indexManager.getDocumentsMatchingTarget(e, n).next((r => {\n const i = __PRIVATE_documentKeySet(...r);\n return this.Ji.getDocuments(e, i).next((r => this.indexManager.getMinOffset(e, n).next((n => {\n const s = this.ts(t, r);\n return this.ns(t, s, i, n.readTime) ? this.Yi(e, __PRIVATE_queryWithLimit(t, null, \"F\" /* LimitType.First */)) : this.rs(e, s, t, n);\n }))));\n })))));\n }\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */ Zi(e, t, n, r) {\n return __PRIVATE_queryMatchesAllDocuments(t) || r.isEqual(SnapshotVersion.min()) ? PersistencePromise.resolve(null) : this.Ji.getDocuments(e, n).next((i => {\n const s = this.ts(t, i);\n return this.ns(t, s, n, r) ? PersistencePromise.resolve(null) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"Re-using previous result from %s to execute query: %s\", r.toString(), __PRIVATE_stringifyQuery(t)), \n this.rs(e, s, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, -1)).next((e => e)));\n }));\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n }\n /** Applies the query filter and sorting to the provided documents. */ ts(e, t) {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let n = new SortedSet(__PRIVATE_newQueryComparator(e));\n return t.forEach(((t, r) => {\n __PRIVATE_queryMatches(e, r) && (n = n.add(r));\n })), n;\n }\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */ ns(e, t, n, r) {\n if (null === e.limit) \n // Queries without limits do not need to be refilled.\n return !1;\n if (n.size !== t.size) \n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return !0;\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const i = \"F\" /* LimitType.First */ === e.limitType ? t.last() : t.first();\n return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0);\n }\n Xi(e, t, n) {\n return __PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"Using full collection scan to execute query:\", __PRIVATE_stringifyQuery(t)), \n this.Ji.getDocumentsMatchingQuery(e, t, IndexOffset.min(), n);\n }\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */ rs(e, t, n, r) {\n // Retrieve all results for documents that were updated since the offset.\n return this.Ji.getDocumentsMatchingQuery(e, n, r).next((e => (\n // Merge with existing results\n t.forEach((t => {\n e = e.insert(t.key, t);\n })), e)));\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/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass __PRIVATE_LocalStoreImpl {\n constructor(\n /** Manages our in-memory or durable persistence. */\n e, t, n, r) {\n this.persistence = e, this.ss = t, this.serializer = r, \n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n this.os = new SortedMap(__PRIVATE_primitiveComparator), \n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n this._s = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), \n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n this.us = new Map, this.cs = e.getRemoteDocumentCache(), this.Ur = e.getTargetCache(), \n this.Gr = e.getBundleCache(), this.ls(n);\n }\n ls(e) {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e), this.indexManager = this.persistence.getIndexManager(e), \n this.mutationQueue = this.persistence.getMutationQueue(e, this.indexManager), this.localDocuments = new LocalDocumentsView(this.cs, this.mutationQueue, this.documentOverlayCache, this.indexManager), \n this.cs.setIndexManager(this.indexManager), this.ss.initialize(this.localDocuments, this.indexManager);\n }\n collectGarbage(e) {\n return this.persistence.runTransaction(\"Collect garbage\", \"readwrite-primary\", (t => e.collect(t, this.os)));\n }\n}\n\nfunction __PRIVATE_newLocalStore(\n/** Manages our in-memory or durable persistence. */\ne, t, n, r) {\n return new __PRIVATE_LocalStoreImpl(e, t, n, r);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nasync function __PRIVATE_localStoreHandleUserChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n return await n.persistence.runTransaction(\"Handle user change\", \"readonly\", (e => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let r;\n return n.mutationQueue.getAllMutationBatches(e).next((i => (r = i, n.ls(t), n.mutationQueue.getAllMutationBatches(e)))).next((t => {\n const i = [], s = [];\n // Union the old/new changed keys.\n let o = __PRIVATE_documentKeySet();\n for (const e of r) {\n i.push(e.batchId);\n for (const t of e.mutations) o = o.add(t.key);\n }\n for (const e of t) {\n s.push(e.batchId);\n for (const t of e.mutations) o = o.add(t.key);\n }\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return n.localDocuments.getDocuments(e, o).next((e => ({\n hs: e,\n removedBatchIds: i,\n addedBatchIds: s\n })));\n }));\n }));\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nfunction __PRIVATE_localStoreAcknowledgeBatch(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Acknowledge batch\", \"readwrite-primary\", (e => {\n const r = t.batch.keys(), i = n.cs.newChangeBuffer({\n trackRemovals: !0\n });\n return function __PRIVATE_applyWriteToRemoteDocuments(e, t, n, r) {\n const i = n.batch, s = i.keys();\n let o = PersistencePromise.resolve();\n return s.forEach((e => {\n o = o.next((() => r.getEntry(t, e))).next((t => {\n const s = n.docVersions.get(e);\n __PRIVATE_hardAssert(null !== s), t.version.compareTo(s) < 0 && (i.applyToRemoteDocument(t, n), \n t.isValidDocument() && (\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n t.setReadTime(n.commitVersion), r.addEntry(t)));\n }));\n })), o.next((() => e.mutationQueue.removeMutationBatch(t, i)));\n }\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-Tab only.\n (n, e, t, i).next((() => i.apply(e))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, function __PRIVATE_getKeysWithTransformResults(e) {\n let t = __PRIVATE_documentKeySet();\n for (let n = 0; n < e.mutationResults.length; ++n) {\n e.mutationResults[n].transformResults.length > 0 && (t = t.add(e.batch.mutations[n].key));\n }\n return t;\n }\n /**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */ (t)))).next((() => n.localDocuments.getDocuments(e, r)));\n }));\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nfunction __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e) {\n const t = __PRIVATE_debugCast(e);\n return t.persistence.runTransaction(\"Get last remote snapshot version\", \"readonly\", (e => t.Ur.getLastRemoteSnapshotVersion(e)));\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */ function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e, t) {\n const n = __PRIVATE_debugCast(e), r = t.snapshotVersion;\n let i = n.os;\n return n.persistence.runTransaction(\"Apply remote event\", \"readwrite-primary\", (e => {\n const s = n.cs.newChangeBuffer({\n trackRemovals: !0\n });\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n i = n.os;\n const o = [];\n t.targetChanges.forEach(((s, _) => {\n const a = i.get(_);\n if (!a) return;\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n o.push(n.Ur.removeMatchingKeys(e, s.removedDocuments, _).next((() => n.Ur.addMatchingKeys(e, s.addedDocuments, _))));\n let u = a.withSequenceNumber(e.currentSequenceNumber);\n null !== t.targetMismatches.get(_) ? u = u.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s.resumeToken.approximateByteSize() > 0 && (u = u.withResumeToken(s.resumeToken, r)), \n i = i.insert(_, u), \n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n /**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\n function __PRIVATE_shouldPersistTargetData(e, t, n) {\n // Always persist target data if we don't already have a resume token.\n if (0 === e.resumeToken.approximateByteSize()) return !0;\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n if (t.snapshotVersion.toMicroseconds() - e.snapshotVersion.toMicroseconds() >= 3e8) return !0;\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;\n }\n /**\n * Notifies local store of the changed views to locally pin documents.\n */ (a, u, s) && o.push(n.Ur.updateTargetData(e, u));\n }));\n let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (t.documentUpdates.forEach((r => {\n t.resolvedLimboDocuments.has(r) && o.push(n.persistence.referenceDelegate.updateLimboDocument(e, r));\n })), \n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n o.push(__PRIVATE_populateDocumentChangeBuffer(e, s, t.documentUpdates).next((e => {\n _ = e.Ps, a = e.Is;\n }))), !r.isEqual(SnapshotVersion.min())) {\n const t = n.Ur.getLastRemoteSnapshotVersion(e).next((t => n.Ur.setTargetsMetadata(e, e.currentSequenceNumber, r)));\n o.push(t);\n }\n return PersistencePromise.waitFor(o).next((() => s.apply(e))).next((() => n.localDocuments.getLocalViewOfDocuments(e, _, a))).next((() => _));\n })).then((e => (n.os = i, e)));\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */ function __PRIVATE_populateDocumentChangeBuffer(e, t, n) {\n let r = __PRIVATE_documentKeySet(), i = __PRIVATE_documentKeySet();\n return n.forEach((e => r = r.add(e))), t.getEntries(e, r).next((e => {\n let r = __PRIVATE_mutableDocumentMap();\n return n.forEach(((n, s) => {\n const o = e.get(n);\n // Check if see if there is a existence state change for this document.\n s.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), \n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n s.isNoDocument() && s.version.isEqual(SnapshotVersion.min()) ? (\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n t.removeEntry(n, s.readTime), r = r.insert(n, s)) : !o.isValidDocument() || s.version.compareTo(o.version) > 0 || 0 === s.version.compareTo(o.version) && o.hasPendingWrites ? (t.addEntry(s), \n r = r.insert(n, s)) : __PRIVATE_logDebug(\"LocalStore\", \"Ignoring outdated watch update for \", n, \". Current version:\", o.version, \" Watch version:\", s.version);\n })), {\n Ps: r,\n Is: i\n };\n }));\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nfunction __PRIVATE_localStoreGetNextMutationBatch(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Get next mutation batch\", \"readonly\", (e => (void 0 === t && (t = -1), \n n.mutationQueue.getNextMutationBatchAfterBatchId(e, t))));\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nfunction __PRIVATE_localStoreAllocateTarget(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Allocate target\", \"readwrite\", (e => {\n let r;\n return n.Ur.getTargetData(e, t).next((i => i ? (\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n r = i, PersistencePromise.resolve(r)) : n.Ur.allocateTargetId(e).next((i => (r = new TargetData(t, i, \"TargetPurposeListen\" /* TargetPurpose.Listen */ , e.currentSequenceNumber), \n n.Ur.addTargetData(e, r).next((() => r)))))));\n })).then((e => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const r = n.os.get(e.targetId);\n return (null === r || e.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.os = n.os.insert(e.targetId, e), \n n._s.set(t, e.targetId)), e;\n }));\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nasync function __PRIVATE_localStoreReleaseTarget(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = r.os.get(t), s = n ? \"readwrite\" : \"readwrite-primary\";\n try {\n n || await r.persistence.runTransaction(\"Release target\", s, (e => r.persistence.referenceDelegate.removeTarget(e, i)));\n } catch (e) {\n if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n __PRIVATE_logDebug(\"LocalStore\", `Failed to update sequence numbers for target ${t}: ${e}`);\n }\n r.os = r.os.remove(t), r._s.delete(i.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */ function __PRIVATE_localStoreExecuteQuery(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n let i = SnapshotVersion.min(), s = __PRIVATE_documentKeySet();\n return r.persistence.runTransaction(\"Execute query\", \"readwrite\", (// Use readwrite instead of readonly so indexes can be created\n // Use readwrite instead of readonly so indexes can be created\n e => function __PRIVATE_localStoreGetTargetData(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = r._s.get(n);\n return void 0 !== i ? PersistencePromise.resolve(r.os.get(i)) : r.Ur.getTargetData(t, n);\n }(r, e, __PRIVATE_queryToTarget(t)).next((t => {\n if (t) return i = t.lastLimboFreeSnapshotVersion, r.Ur.getMatchingKeysForTargetId(e, t.targetId).next((e => {\n s = e;\n }));\n })).next((() => r.ss.getDocumentsMatchingQuery(e, t, n ? i : SnapshotVersion.min(), n ? s : __PRIVATE_documentKeySet()))).next((e => (__PRIVATE_setMaxReadTime(r, __PRIVATE_queryCollectionGroup(t), e), \n {\n documents: e,\n Ts: s\n })))));\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_localStoreGetCachedTarget(e, t) {\n const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.Ur), i = n.os.get(t);\n return i ? Promise.resolve(i.target) : n.persistence.runTransaction(\"Get target data\", \"readonly\", (e => r.ot(e, t).next((e => e ? e.target : null))));\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_localStoreGetNewDocumentChanges(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.us.get(t) || SnapshotVersion.min();\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n return n.persistence.runTransaction(\"Get new document changes\", \"readonly\", (e => n.cs.getAllFromCollectionGroup(e, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, -1), \n /* limit= */ Number.MAX_SAFE_INTEGER))).then((e => (__PRIVATE_setMaxReadTime(n, t, e), \n e)));\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_setMaxReadTime(e, t, n) {\n let r = e.us.get(t) || SnapshotVersion.min();\n n.forEach(((e, t) => {\n t.readTime.compareTo(r) > 0 && (r = t.readTime);\n })), e.us.set(t, r);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nasync function __PRIVATE_localStoreApplyBundledDocuments(e, t, n, r) {\n const i = __PRIVATE_debugCast(e);\n let s = __PRIVATE_documentKeySet(), o = __PRIVATE_mutableDocumentMap();\n for (const e of n) {\n const n = t.Es(e.metadata.name);\n e.document && (s = s.add(n));\n const r = t.ds(e);\n r.setReadTime(t.As(e.metadata.readTime)), o = o.insert(n, r);\n }\n const _ = i.cs.newChangeBuffer({\n trackRemovals: !0\n }), a = await __PRIVATE_localStoreAllocateTarget(i, function __PRIVATE_umbrellaTarget(e) {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`)));\n }(r));\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n return i.persistence.runTransaction(\"Apply bundle documents\", \"readwrite\", (e => __PRIVATE_populateDocumentChangeBuffer(e, _, o).next((t => (_.apply(e), \n t))).next((t => i.Ur.removeMatchingKeysForTargetId(e, a.targetId).next((() => i.Ur.addMatchingKeys(e, s, a.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(e, t.Ps, t.Is))).next((() => t.Ps))))));\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nasync function __PRIVATE_localStoreSaveNamedQuery(e, t, n = __PRIVATE_documentKeySet()) {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const r = await __PRIVATE_localStoreAllocateTarget(e, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t.bundledQuery))), i = __PRIVATE_debugCast(e);\n return i.persistence.runTransaction(\"Save named query\", \"readwrite\", (e => {\n const s = __PRIVATE_fromVersion(t.readTime);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (r.snapshotVersion.compareTo(s) >= 0) return i.Gr.saveNamedQuery(e, t);\n // Update existing target data because the query from the bundle is newer.\n const o = r.withResumeToken(ByteString.EMPTY_BYTE_STRING, s);\n return i.os = i.os.insert(o.targetId, o), i.Ur.updateTargetData(e, o).next((() => i.Ur.removeMatchingKeysForTargetId(e, r.targetId))).next((() => i.Ur.addMatchingKeys(e, n, r.targetId))).next((() => i.Gr.saveNamedQuery(e, t)));\n }));\n}\n\n/** Assembles the key for a client state in WebStorage */\nfunction createWebStorageClientStateKey(e, t) {\n return `firestore_clients_${e}_${t}`;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n/** Assembles the key for a mutation batch in WebStorage */\nfunction createWebStorageMutationBatchKey(e, t, n) {\n let r = `firestore_mutations_${e}_${n}`;\n return t.isAuthenticated() && (r += `_${t.uid}`), r;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\n/** Assembles the key for a query state in WebStorage */\nfunction createWebStorageQueryTargetMetadataKey(e, t) {\n return `firestore_targets_${e}_${t}`;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nclass __PRIVATE_MutationMetadata {\n constructor(e, t, n, r) {\n this.user = e, this.batchId = t, this.state = n, this.error = r;\n }\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Rs(e, t, n) {\n const r = JSON.parse(n);\n let i, s = \"object\" == typeof r && -1 !== [ \"pending\", \"acknowledged\", \"rejected\" ].indexOf(r.state) && (void 0 === r.error || \"object\" == typeof r.error);\n return s && r.error && (s = \"string\" == typeof r.error.message && \"string\" == typeof r.error.code, \n s && (i = new FirestoreError(r.error.code, r.error.message))), s ? new __PRIVATE_MutationMetadata(e, t, r.state, i) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse mutation state for ID '${t}': ${n}`), \n null);\n }\n Vs() {\n const e = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (e.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(e);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nclass __PRIVATE_QueryTargetMetadata {\n constructor(e, t, n) {\n this.targetId = e, this.state = t, this.error = n;\n }\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Rs(e, t) {\n const n = JSON.parse(t);\n let r, i = \"object\" == typeof n && -1 !== [ \"not-current\", \"current\", \"rejected\" ].indexOf(n.state) && (void 0 === n.error || \"object\" == typeof n.error);\n return i && n.error && (i = \"string\" == typeof n.error.message && \"string\" == typeof n.error.code, \n i && (r = new FirestoreError(n.error.code, n.error.message))), i ? new __PRIVATE_QueryTargetMetadata(e, n.state, r) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse target state for ID '${e}': ${t}`), \n null);\n }\n Vs() {\n const e = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (e.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(e);\n }\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */ class __PRIVATE_RemoteClientState {\n constructor(e, t) {\n this.clientId = e, this.activeTargetIds = t;\n }\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Rs(e, t) {\n const n = JSON.parse(t);\n let r = \"object\" == typeof n && n.activeTargetIds instanceof Array, i = __PRIVATE_targetIdSet();\n for (let e = 0; r && e < n.activeTargetIds.length; ++e) r = isSafeInteger(n.activeTargetIds[e]), \n i = i.add(n.activeTargetIds[e]);\n return r ? new __PRIVATE_RemoteClientState(e, i) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse client data for instance '${e}': ${t}`), \n null);\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */ class __PRIVATE_SharedOnlineState {\n constructor(e, t) {\n this.clientId = e, this.onlineState = t;\n }\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Rs(e) {\n const t = JSON.parse(e);\n return \"object\" == typeof t && -1 !== [ \"Unknown\", \"Online\", \"Offline\" ].indexOf(t.onlineState) && \"string\" == typeof t.clientId ? new __PRIVATE_SharedOnlineState(t.clientId, t.onlineState) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse online state: ${e}`), \n null);\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nclass __PRIVATE_LocalClientState {\n constructor() {\n this.activeTargetIds = __PRIVATE_targetIdSet();\n }\n fs(e) {\n this.activeTargetIds = this.activeTargetIds.add(e);\n }\n gs(e) {\n this.activeTargetIds = this.activeTargetIds.delete(e);\n }\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */ Vs() {\n const e = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now()\n };\n return JSON.stringify(e);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */ class __PRIVATE_WebStorageSharedClientState {\n constructor(e, t, n, r, i) {\n this.window = e, this.ui = t, this.persistenceKey = n, this.ps = r, this.syncEngine = null, \n this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.ys = this.ws.bind(this), \n this.Ss = new SortedMap(__PRIVATE_primitiveComparator), this.started = !1, \n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n this.bs = [];\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const s = n.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n this.storage = this.window.localStorage, this.currentUser = i, this.Ds = createWebStorageClientStateKey(this.persistenceKey, this.ps), \n this.vs = \n /** Assembles the key for the current sequence number. */\n function createWebStorageSequenceNumberKey(e) {\n return `firestore_sequence_number_${e}`;\n }\n /**\n * @license\n * Copyright 2018 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 */ (this.persistenceKey), this.Ss = this.Ss.insert(this.ps, new __PRIVATE_LocalClientState), \n this.Cs = new RegExp(`^firestore_clients_${s}_([^_]*)$`), this.Fs = new RegExp(`^firestore_mutations_${s}_(\\\\d+)(?:_(.*))?$`), \n this.Ms = new RegExp(`^firestore_targets_${s}_(\\\\d+)$`), this.xs = \n /** Assembles the key for the online state of the primary tab. */\n function createWebStorageOnlineStateKey(e) {\n return `firestore_online_state_${e}`;\n }\n // The WebStorage prefix that plays as a event to indicate the remote documents\n // might have changed due to some secondary tabs loading a bundle.\n // format of the key is:\n // firestore_bundle_loaded_v2_\n // The version ending with \"v2\" stores the list of modified collection groups.\n (this.persistenceKey), this.Os = function createBundleLoadedKey(e) {\n return `firestore_bundle_loaded_v2_${e}`;\n }\n // The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n // looks like 'firestore_sequence_number_'.\n (this.persistenceKey), \n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener(\"storage\", this.ys);\n }\n /** Returns 'true' if WebStorage is available in the current environment. */ static D(e) {\n return !(!e || !e.localStorage);\n }\n async start() {\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const e = await this.syncEngine.Qi();\n for (const t of e) {\n if (t === this.ps) continue;\n const e = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t));\n if (e) {\n const n = __PRIVATE_RemoteClientState.Rs(t, e);\n n && (this.Ss = this.Ss.insert(n.clientId, n));\n }\n }\n this.Ns();\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const t = this.storage.getItem(this.xs);\n if (t) {\n const e = this.Ls(t);\n e && this.Bs(e);\n }\n for (const e of this.bs) this.ws(e);\n this.bs = [], \n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener(\"pagehide\", (() => this.shutdown())), this.started = !0;\n }\n writeSequenceNumber(e) {\n this.setItem(this.vs, JSON.stringify(e));\n }\n getAllActiveQueryTargets() {\n return this.ks(this.Ss);\n }\n isActiveQueryTarget(e) {\n let t = !1;\n return this.Ss.forEach(((n, r) => {\n r.activeTargetIds.has(e) && (t = !0);\n })), t;\n }\n addPendingMutation(e) {\n this.qs(e, \"pending\");\n }\n updateMutationState(e, t, n) {\n this.qs(e, t, n), \n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.Qs(e);\n }\n addLocalQueryTarget(e, t = !0) {\n let n = \"not-current\";\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(e)) {\n const t = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));\n if (t) {\n const r = __PRIVATE_QueryTargetMetadata.Rs(e, t);\n r && (n = r.state);\n }\n }\n // If the query is listening to cache only, the target ID should not be registered with the\n // local Firestore client as an active watch target.\n return t && this.Ks.fs(e), this.Ns(), n;\n }\n removeLocalQueryTarget(e) {\n this.Ks.gs(e), this.Ns();\n }\n isLocalQueryTarget(e) {\n return this.Ks.activeTargetIds.has(e);\n }\n clearQueryState(e) {\n this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));\n }\n updateQueryState(e, t, n) {\n this.$s(e, t, n);\n }\n handleUserChange(e, t, n) {\n t.forEach((e => {\n this.Qs(e);\n })), this.currentUser = e, n.forEach((e => {\n this.addPendingMutation(e);\n }));\n }\n setOnlineState(e) {\n this.Us(e);\n }\n notifyBundleLoaded(e) {\n this.Ws(e);\n }\n shutdown() {\n this.started && (this.window.removeEventListener(\"storage\", this.ys), this.removeItem(this.Ds), \n this.started = !1);\n }\n getItem(e) {\n const t = this.storage.getItem(e);\n return __PRIVATE_logDebug(\"SharedClientState\", \"READ\", e, t), t;\n }\n setItem(e, t) {\n __PRIVATE_logDebug(\"SharedClientState\", \"SET\", e, t), this.storage.setItem(e, t);\n }\n removeItem(e) {\n __PRIVATE_logDebug(\"SharedClientState\", \"REMOVE\", e), this.storage.removeItem(e);\n }\n ws(e) {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const t = e;\n if (t.storageArea === this.storage) {\n if (__PRIVATE_logDebug(\"SharedClientState\", \"EVENT\", t.key, t.newValue), t.key === this.Ds) return void __PRIVATE_logError(\"Received WebStorage notification for local change. Another client might have garbage-collected our state\");\n this.ui.enqueueRetryable((async () => {\n if (this.started) {\n if (null !== t.key) if (this.Cs.test(t.key)) {\n if (null == t.newValue) {\n const e = this.Gs(t.key);\n return this.zs(e, null);\n }\n {\n const e = this.js(t.key, t.newValue);\n if (e) return this.zs(e.clientId, e);\n }\n } else if (this.Fs.test(t.key)) {\n if (null !== t.newValue) {\n const e = this.Hs(t.key, t.newValue);\n if (e) return this.Js(e);\n }\n } else if (this.Ms.test(t.key)) {\n if (null !== t.newValue) {\n const e = this.Ys(t.key, t.newValue);\n if (e) return this.Zs(e);\n }\n } else if (t.key === this.xs) {\n if (null !== t.newValue) {\n const e = this.Ls(t.newValue);\n if (e) return this.Bs(e);\n }\n } else if (t.key === this.vs) {\n const e = function __PRIVATE_fromWebStorageSequenceNumber(e) {\n let t = __PRIVATE_ListenSequence.oe;\n if (null != e) try {\n const n = JSON.parse(e);\n __PRIVATE_hardAssert(\"number\" == typeof n), t = n;\n } catch (e) {\n __PRIVATE_logError(\"SharedClientState\", \"Failed to read sequence number from WebStorage\", e);\n }\n return t;\n }\n /**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */ (t.newValue);\n e !== __PRIVATE_ListenSequence.oe && this.sequenceNumberHandler(e);\n } else if (t.key === this.Os) {\n const e = this.Xs(t.newValue);\n await Promise.all(e.map((e => this.syncEngine.eo(e))));\n }\n } else this.bs.push(t);\n }));\n }\n }\n get Ks() {\n return this.Ss.get(this.ps);\n }\n Ns() {\n this.setItem(this.Ds, this.Ks.Vs());\n }\n qs(e, t, n) {\n const r = new __PRIVATE_MutationMetadata(this.currentUser, e, t, n), i = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);\n this.setItem(i, r.Vs());\n }\n Qs(e) {\n const t = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);\n this.removeItem(t);\n }\n Us(e) {\n const t = {\n clientId: this.ps,\n onlineState: e\n };\n this.storage.setItem(this.xs, JSON.stringify(t));\n }\n $s(e, t, n) {\n const r = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e), i = new __PRIVATE_QueryTargetMetadata(e, t, n);\n this.setItem(r, i.Vs());\n }\n Ws(e) {\n const t = JSON.stringify(Array.from(e));\n this.setItem(this.Os, t);\n }\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */ Gs(e) {\n const t = this.Cs.exec(e);\n return t ? t[1] : null;\n }\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */ js(e, t) {\n const n = this.Gs(e);\n return __PRIVATE_RemoteClientState.Rs(n, t);\n }\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Hs(e, t) {\n const n = this.Fs.exec(e), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;\n return __PRIVATE_MutationMetadata.Rs(new User(i), r, t);\n }\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Ys(e, t) {\n const n = this.Ms.exec(e), r = Number(n[1]);\n return __PRIVATE_QueryTargetMetadata.Rs(r, t);\n }\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Ls(e) {\n return __PRIVATE_SharedOnlineState.Rs(e);\n }\n Xs(e) {\n return JSON.parse(e);\n }\n async Js(e) {\n if (e.user.uid === this.currentUser.uid) return this.syncEngine.no(e.batchId, e.state, e.error);\n __PRIVATE_logDebug(\"SharedClientState\", `Ignoring mutation for non-active user ${e.user.uid}`);\n }\n Zs(e) {\n return this.syncEngine.ro(e.targetId, e.state, e.error);\n }\n zs(e, t) {\n const n = t ? this.Ss.insert(e, t) : this.Ss.remove(e), r = this.ks(this.Ss), i = this.ks(n), s = [], o = [];\n return i.forEach((e => {\n r.has(e) || s.push(e);\n })), r.forEach((e => {\n i.has(e) || o.push(e);\n })), this.syncEngine.io(s, o).then((() => {\n this.Ss = n;\n }));\n }\n Bs(e) {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n this.Ss.get(e.clientId) && this.onlineStateHandler(e.onlineState);\n }\n ks(e) {\n let t = __PRIVATE_targetIdSet();\n return e.forEach(((e, n) => {\n t = t.unionWith(n.activeTargetIds);\n })), t;\n }\n}\n\nclass __PRIVATE_MemorySharedClientState {\n constructor() {\n this.so = new __PRIVATE_LocalClientState, this.oo = {}, this.onlineStateHandler = null, \n this.sequenceNumberHandler = null;\n }\n addPendingMutation(e) {\n // No op.\n }\n updateMutationState(e, t, n) {\n // No op.\n }\n addLocalQueryTarget(e, t = !0) {\n return t && this.so.fs(e), this.oo[e] || \"not-current\";\n }\n updateQueryState(e, t, n) {\n this.oo[e] = t;\n }\n removeLocalQueryTarget(e) {\n this.so.gs(e);\n }\n isLocalQueryTarget(e) {\n return this.so.activeTargetIds.has(e);\n }\n clearQueryState(e) {\n delete this.oo[e];\n }\n getAllActiveQueryTargets() {\n return this.so.activeTargetIds;\n }\n isActiveQueryTarget(e) {\n return this.so.activeTargetIds.has(e);\n }\n start() {\n return this.so = new __PRIVATE_LocalClientState, Promise.resolve();\n }\n handleUserChange(e, t, n) {\n // No op.\n }\n setOnlineState(e) {\n // No op.\n }\n shutdown() {}\n writeSequenceNumber(e) {}\n notifyBundleLoaded(e) {\n // No op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_NoopConnectivityMonitor {\n _o(e) {\n // No-op.\n }\n shutdown() {\n // No-op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nclass __PRIVATE_BrowserConnectivityMonitor {\n constructor() {\n this.ao = () => this.uo(), this.co = () => this.lo(), this.ho = [], this.Po();\n }\n _o(e) {\n this.ho.push(e);\n }\n shutdown() {\n window.removeEventListener(\"online\", this.ao), window.removeEventListener(\"offline\", this.co);\n }\n Po() {\n window.addEventListener(\"online\", this.ao), window.addEventListener(\"offline\", this.co);\n }\n uo() {\n __PRIVATE_logDebug(\"ConnectivityMonitor\", \"Network connectivity changed: AVAILABLE\");\n for (const e of this.ho) e(0 /* NetworkStatus.AVAILABLE */);\n }\n lo() {\n __PRIVATE_logDebug(\"ConnectivityMonitor\", \"Network connectivity changed: UNAVAILABLE\");\n for (const e of this.ho) e(1 /* NetworkStatus.UNAVAILABLE */);\n }\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static D() {\n return \"undefined\" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;\n }\n}\n\n/**\n * @license\n * Copyright 2023 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 * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */ let me = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nfunction __PRIVATE_generateUniqueDebugId() {\n return null === me ? me = function __PRIVATE_generateInitialUniqueDebugId() {\n return 268435456 + Math.round(2147483648 * Math.random());\n }() : me++, \"0x\" + me.toString(16);\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 */ const fe = {\n BatchGetDocuments: \"batchGet\",\n Commit: \"commit\",\n RunQuery: \"runQuery\",\n RunAggregationQuery: \"runAggregationQuery\"\n};\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nclass __PRIVATE_StreamBridge {\n constructor(e) {\n this.Io = e.Io, this.To = e.To;\n }\n Eo(e) {\n this.Ao = e;\n }\n Ro(e) {\n this.Vo = e;\n }\n mo(e) {\n this.fo = e;\n }\n onMessage(e) {\n this.po = e;\n }\n close() {\n this.To();\n }\n send(e) {\n this.Io(e);\n }\n yo() {\n this.Ao();\n }\n wo() {\n this.Vo();\n }\n So(e) {\n this.fo(e);\n }\n bo(e) {\n this.po(e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const ge = \"WebChannelConnection\";\n\nclass __PRIVATE_WebChannelConnection extends \n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nclass __PRIVATE_RestConnection {\n constructor(e) {\n this.databaseInfo = e, this.databaseId = e.databaseId;\n const t = e.ssl ? \"https\" : \"http\", n = encodeURIComponent(this.databaseId.projectId), r = encodeURIComponent(this.databaseId.database);\n this.Do = t + \"://\" + e.host, this.vo = `projects/${n}/databases/${r}`, this.Co = \"(default)\" === this.databaseId.database ? `project_id=${n}` : `project_id=${n}&database_id=${r}`;\n }\n get Fo() {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return !1;\n }\n Mo(e, t, n, r, i) {\n const s = __PRIVATE_generateUniqueDebugId(), o = this.xo(e, t.toUriEncodedString());\n __PRIVATE_logDebug(\"RestConnection\", `Sending RPC '${e}' ${s}:`, o, n);\n const _ = {\n \"google-cloud-resource-prefix\": this.vo,\n \"x-goog-request-params\": this.Co\n };\n return this.Oo(_, r, i), this.No(e, o, _, n).then((t => (__PRIVATE_logDebug(\"RestConnection\", `Received RPC '${e}' ${s}: `, t), \n t)), (t => {\n throw __PRIVATE_logWarn(\"RestConnection\", `RPC '${e}' ${s} failed with error: `, t, \"url: \", o, \"request:\", n), \n t;\n }));\n }\n Lo(e, t, n, r, i, s) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.Mo(e, t, n, r, i);\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */ Oo(e, t, n) {\n e[\"X-Goog-Api-Client\"] = \n // SDK_VERSION is updated to different value at runtime depending on the entry point,\n // so we need to get its value when we need it in a function.\n function __PRIVATE_getGoogApiClientValue() {\n return \"gl-js/ fire/\" + S;\n }(), \n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n e[\"Content-Type\"] = \"text/plain\", this.databaseInfo.appId && (e[\"X-Firebase-GMPID\"] = this.databaseInfo.appId), \n t && t.headers.forEach(((t, n) => e[n] = t)), n && n.headers.forEach(((t, n) => e[n] = t));\n }\n xo(e, t) {\n const n = fe[e];\n return `${this.Do}/v1/${t}:${n}`;\n }\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */ terminate() {\n // No-op\n }\n} {\n constructor(e) {\n super(e), this.forceLongPolling = e.forceLongPolling, this.autoDetectLongPolling = e.autoDetectLongPolling, \n this.useFetchStreams = e.useFetchStreams, this.longPollingOptions = e.longPollingOptions;\n }\n No(e, t, n, r) {\n const i = __PRIVATE_generateUniqueDebugId();\n return new Promise(((s, o) => {\n const _ = new XhrIo;\n _.setWithCredentials(!0), _.listenOnce(EventType.COMPLETE, (() => {\n try {\n switch (_.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const t = _.getResponseJson();\n __PRIVATE_logDebug(ge, `XHR for RPC '${e}' ${i} received:`, JSON.stringify(t)), \n s(t);\n break;\n\n case ErrorCode.TIMEOUT:\n __PRIVATE_logDebug(ge, `RPC '${e}' ${i} timed out`), o(new FirestoreError(D.DEADLINE_EXCEEDED, \"Request time out\"));\n break;\n\n case ErrorCode.HTTP_ERROR:\n const n = _.getStatus();\n if (__PRIVATE_logDebug(ge, `RPC '${e}' ${i} failed with status:`, n, \"response text:\", _.getResponseText()), \n n > 0) {\n let e = _.getResponseJson();\n Array.isArray(e) && (e = e[0]);\n const t = null == e ? void 0 : e.error;\n if (t && t.status && t.message) {\n const e = function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e) {\n const t = e.toLowerCase().replace(/_/g, \"-\");\n return Object.values(D).indexOf(t) >= 0 ? t : D.UNKNOWN;\n }(t.status);\n o(new FirestoreError(e, t.message));\n } else o(new FirestoreError(D.UNKNOWN, \"Server responded with status \" + _.getStatus()));\n } else \n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n o(new FirestoreError(D.UNAVAILABLE, \"Connection failed.\"));\n break;\n\n default:\n fail();\n }\n } finally {\n __PRIVATE_logDebug(ge, `RPC '${e}' ${i} completed.`);\n }\n }));\n const a = JSON.stringify(r);\n __PRIVATE_logDebug(ge, `RPC '${e}' ${i} sending request:`, r), _.send(t, \"POST\", a, n, 15);\n }));\n }\n Bo(e, t, n) {\n const r = __PRIVATE_generateUniqueDebugId(), i = [ this.Do, \"/\", \"google.firestore.v1.Firestore\", \"/\", e, \"/channel\" ], s = createWebChannelTransport(), o = getStatEventTarget(), _ = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: \"gsessionid\",\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: !0,\n supportsCrossDomainXhr: !0,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 6e5\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n }, a = this.longPollingOptions.timeoutSeconds;\n void 0 !== a && (_.longPollingTimeout = Math.round(1e3 * a)), this.useFetchStreams && (_.useFetchStreams = !0), \n this.Oo(_.initMessageHeaders, t, n), \n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n _.encodeInitMessageHeaders = !0;\n const u = i.join(\"\");\n __PRIVATE_logDebug(ge, `Creating RPC '${e}' stream ${r}: ${u}`, _);\n const c = s.createWebChannel(u, _);\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let l = !1, h = !1;\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n const P = new __PRIVATE_StreamBridge({\n Io: t => {\n h ? __PRIVATE_logDebug(ge, `Not sending because RPC '${e}' stream ${r} is closed:`, t) : (l || (__PRIVATE_logDebug(ge, `Opening RPC '${e}' stream ${r} transport.`), \n c.open(), l = !0), __PRIVATE_logDebug(ge, `RPC '${e}' stream ${r} sending:`, t), \n c.send(t));\n },\n To: () => c.close()\n }), __PRIVATE_unguardedEventListen = (e, t, n) => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n e.listen(t, (e => {\n try {\n n(e);\n } catch (e) {\n setTimeout((() => {\n throw e;\n }), 0);\n }\n }));\n };\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n return __PRIVATE_unguardedEventListen(c, WebChannel.EventType.OPEN, (() => {\n h || (__PRIVATE_logDebug(ge, `RPC '${e}' stream ${r} transport opened.`), P.yo());\n })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.CLOSE, (() => {\n h || (h = !0, __PRIVATE_logDebug(ge, `RPC '${e}' stream ${r} transport closed`), \n P.So());\n })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.ERROR, (t => {\n h || (h = !0, __PRIVATE_logWarn(ge, `RPC '${e}' stream ${r} transport errored:`, t), \n P.So(new FirestoreError(D.UNAVAILABLE, \"The operation could not be completed\")));\n })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.MESSAGE, (t => {\n var n;\n if (!h) {\n const i = t.data[0];\n __PRIVATE_hardAssert(!!i);\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const s = i, o = s.error || (null === (n = s[0]) || void 0 === n ? void 0 : n.error);\n if (o) {\n __PRIVATE_logDebug(ge, `RPC '${e}' stream ${r} received error:`, o);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const t = o.status;\n let n = \n /**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\n function __PRIVATE_mapCodeFromRpcStatus(e) {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const t = le[e];\n if (void 0 !== t) return __PRIVATE_mapCodeFromRpcCode(t);\n }(t), i = o.message;\n void 0 === n && (n = D.INTERNAL, i = \"Unknown error status: \" + t + \" with message \" + o.message), \n // Mark closed so no further events are propagated\n h = !0, P.So(new FirestoreError(n, i)), c.close();\n } else __PRIVATE_logDebug(ge, `RPC '${e}' stream ${r} received:`, i), P.bo(i);\n }\n })), __PRIVATE_unguardedEventListen(o, Event.STAT_EVENT, (t => {\n t.stat === Stat.PROXY ? __PRIVATE_logDebug(ge, `RPC '${e}' stream ${r} detected buffering proxy`) : t.stat === Stat.NOPROXY && __PRIVATE_logDebug(ge, `RPC '${e}' stream ${r} detected no buffering proxy`);\n })), setTimeout((() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n P.wo();\n }), 0), P;\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/** Initializes the WebChannelConnection for the browser. */\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/** The Platform's 'window' implementation or null if not available. */\nfunction __PRIVATE_getWindow() {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof window ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */ function getDocument() {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof document ? document : 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 */ function __PRIVATE_newSerializer(e) {\n return new JsonProtoSerializer(e, /* useProto3Json= */ !0);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nclass __PRIVATE_ExponentialBackoff {\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n e, \n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n t, \n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n n = 1e3\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */ , r = 1.5\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */ , i = 6e4) {\n this.ui = e, this.timerId = t, this.ko = n, this.qo = r, this.Qo = i, this.Ko = 0, \n this.$o = null, \n /** The last backoff attempt, as epoch milliseconds. */\n this.Uo = Date.now(), this.reset();\n }\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */ reset() {\n this.Ko = 0;\n }\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */ Wo() {\n this.Ko = this.Qo;\n }\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */ Go(e) {\n // Cancel any pending backoff operation.\n this.cancel();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const t = Math.floor(this.Ko + this.zo()), n = Math.max(0, Date.now() - this.Uo), r = Math.max(0, t - n);\n // Guard against lastAttemptTime being in the future due to a clock change.\n r > 0 && __PRIVATE_logDebug(\"ExponentialBackoff\", `Backing off for ${r} ms (base delay: ${this.Ko} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`), \n this.$o = this.ui.enqueueAfterDelay(this.timerId, r, (() => (this.Uo = Date.now(), \n e()))), \n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.Ko *= this.qo, this.Ko < this.ko && (this.Ko = this.ko), this.Ko > this.Qo && (this.Ko = this.Qo);\n }\n jo() {\n null !== this.$o && (this.$o.skipDelay(), this.$o = null);\n }\n cancel() {\n null !== this.$o && (this.$o.cancel(), this.$o = null);\n }\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ zo() {\n return (Math.random() - .5) * this.Ko;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nclass __PRIVATE_PersistentStream {\n constructor(e, t, n, r, i, s, o, _) {\n this.ui = e, this.Ho = n, this.Jo = r, this.connection = i, this.authCredentialsProvider = s, \n this.appCheckCredentialsProvider = o, this.listener = _, this.state = 0 /* PersistentStreamState.Initial */ , \n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n this.Yo = 0, this.Zo = null, this.Xo = null, this.stream = null, \n /**\n * Count of response messages received.\n */\n this.e_ = 0, this.t_ = new __PRIVATE_ExponentialBackoff(e, t);\n }\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */ n_() {\n return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.r_();\n }\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */ r_() {\n return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;\n }\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */ start() {\n this.e_ = 0, 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.i_();\n }\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */ async stop() {\n this.n_() && await this.close(0 /* PersistentStreamState.Initial */);\n }\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */ s_() {\n this.state = 0 /* PersistentStreamState.Initial */ , this.t_.reset();\n }\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */ o_() {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n this.r_() && null === this.Zo && (this.Zo = this.ui.enqueueAfterDelay(this.Ho, 6e4, (() => this.__())));\n }\n /** Sends a message to the underlying stream. */ a_(e) {\n this.u_(), this.stream.send(e);\n }\n /** Called by the idle timer when the stream should close due to inactivity. */ async __() {\n if (this.r_()) \n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(0 /* PersistentStreamState.Initial */);\n }\n /** Marks the stream as active again. */ u_() {\n this.Zo && (this.Zo.cancel(), this.Zo = null);\n }\n /** Cancels the health check delayed operation. */ c_() {\n this.Xo && (this.Xo.cancel(), this.Xo = null);\n }\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */ async close(e, t) {\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.u_(), this.c_(), this.t_.cancel(), \n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.Yo++, 4 /* PersistentStreamState.Error */ !== e ? \n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.t_.reset() : t && t.code === D.RESOURCE_EXHAUSTED ? (\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n __PRIVATE_logError(t.toString()), __PRIVATE_logError(\"Using maximum backoff delay to prevent overloading the backend.\"), \n this.t_.Wo()) : t && t.code === D.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), \n // Clean up the underlying stream because we are no longer interested in events.\n null !== this.stream && (this.l_(), this.stream.close(), this.stream = null), \n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = e, \n // Notify the listener that the stream closed.\n await this.listener.mo(t);\n }\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */ l_() {}\n auth() {\n this.state = 1 /* PersistentStreamState.Starting */;\n const e = this.h_(this.Yo), t = this.Yo;\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([e, n]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n this.Yo === t && \n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.P_(e, n);\n }), (t => {\n e((() => {\n const e = new FirestoreError(D.UNKNOWN, \"Fetching auth token failed: \" + t.message);\n return this.I_(e);\n }));\n }));\n }\n P_(e, t) {\n const n = this.h_(this.Yo);\n this.stream = this.T_(e, t), this.stream.Eo((() => {\n n((() => this.listener.Eo()));\n })), this.stream.Ro((() => {\n n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Xo = this.ui.enqueueAfterDelay(this.Jo, 1e4, (() => (this.r_() && (this.state = 3 /* PersistentStreamState.Healthy */), \n Promise.resolve()))), this.listener.Ro())));\n })), this.stream.mo((e => {\n n((() => this.I_(e)));\n })), this.stream.onMessage((e => {\n n((() => 1 == ++this.e_ ? this.E_(e) : this.onNext(e)));\n }));\n }\n i_() {\n this.state = 5 /* PersistentStreamState.Backoff */ , this.t_.Go((async () => {\n this.state = 0 /* PersistentStreamState.Initial */ , this.start();\n }));\n }\n // Visible for tests\n I_(e) {\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return __PRIVATE_logDebug(\"PersistentStream\", `close with error: ${e}`), this.stream = null, \n this.close(4 /* PersistentStreamState.Error */ , e);\n }\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */ h_(e) {\n return t => {\n this.ui.enqueueAndForget((() => this.Yo === e ? t() : (__PRIVATE_logDebug(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), \n Promise.resolve())));\n };\n }\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */ class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream {\n constructor(e, t, n, r, i, s) {\n super(e, \"listen_stream_connection_backoff\" /* TimerId.ListenStreamConnectionBackoff */ , \"listen_stream_idle\" /* TimerId.ListenStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , t, n, r, s), \n this.serializer = i;\n }\n T_(e, t) {\n return this.connection.Bo(\"Listen\", e, t);\n }\n E_(e) {\n return this.onNext(e);\n }\n onNext(e) {\n // A successful response means the stream is healthy\n this.t_.reset();\n const t = __PRIVATE_fromWatchChange(this.serializer, e), n = function __PRIVATE_versionFromListenResponse(e) {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!(\"targetChange\" in e)) return SnapshotVersion.min();\n const t = e.targetChange;\n return t.targetIds && t.targetIds.length ? SnapshotVersion.min() : t.readTime ? __PRIVATE_fromVersion(t.readTime) : SnapshotVersion.min();\n }(e);\n return this.listener.d_(t, n);\n }\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */ A_(e) {\n const t = {};\n t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.addTarget = function __PRIVATE_toTarget(e, t) {\n let n;\n const r = t.target;\n if (n = __PRIVATE_targetIsDocumentTarget(r) ? {\n documents: __PRIVATE_toDocumentsTarget(e, r)\n } : {\n query: __PRIVATE_toQueryTarget(e, r)._t\n }, n.targetId = t.targetId, t.resumeToken.approximateByteSize() > 0) {\n n.resumeToken = __PRIVATE_toBytes(e, t.resumeToken);\n const r = __PRIVATE_toInt32Proto(e, t.expectedCount);\n null !== r && (n.expectedCount = r);\n } else if (t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n n.readTime = toTimestamp(e, t.snapshotVersion.toTimestamp());\n const r = __PRIVATE_toInt32Proto(e, t.expectedCount);\n null !== r && (n.expectedCount = r);\n }\n return n;\n }(this.serializer, e);\n const n = __PRIVATE_toListenRequestLabels(this.serializer, e);\n n && (t.labels = n), this.a_(t);\n }\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */ R_(e) {\n const t = {};\n t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.removeTarget = e, \n this.a_(t);\n }\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */ class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream {\n constructor(e, t, n, r, i, s) {\n super(e, \"write_stream_connection_backoff\" /* TimerId.WriteStreamConnectionBackoff */ , \"write_stream_idle\" /* TimerId.WriteStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , t, n, r, s), \n this.serializer = i;\n }\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */ get V_() {\n return this.e_ > 0;\n }\n // Override of PersistentStream.start\n start() {\n this.lastStreamToken = void 0, super.start();\n }\n l_() {\n this.V_ && this.m_([]);\n }\n T_(e, t) {\n return this.connection.Bo(\"Write\", e, t);\n }\n E_(e) {\n // Always capture the last stream token.\n return __PRIVATE_hardAssert(!!e.streamToken), this.lastStreamToken = e.streamToken, \n // The first response is always the handshake response\n __PRIVATE_hardAssert(!e.writeResults || 0 === e.writeResults.length), this.listener.f_();\n }\n onNext(e) {\n // Always capture the last stream token.\n __PRIVATE_hardAssert(!!e.streamToken), this.lastStreamToken = e.streamToken, \n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.t_.reset();\n const t = __PRIVATE_fromWriteResults(e.writeResults, e.commitTime), n = __PRIVATE_fromVersion(e.commitTime);\n return this.listener.g_(n, t);\n }\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */ p_() {\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const e = {};\n e.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.a_(e);\n }\n /** Sends a group of mutations to the Firestore backend to apply. */ m_(e) {\n const t = {\n streamToken: this.lastStreamToken,\n writes: e.map((e => toMutation(this.serializer, e)))\n };\n this.a_(t);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass __PRIVATE_DatastoreImpl extends class Datastore {} {\n constructor(e, t, n, r) {\n super(), this.authCredentials = e, this.appCheckCredentials = t, this.connection = n, \n this.serializer = r, this.y_ = !1;\n }\n w_() {\n if (this.y_) throw new FirestoreError(D.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n /** Invokes the provided RPC with auth and AppCheck tokens. */ Mo(e, t, n, r) {\n return this.w_(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.Mo(e, __PRIVATE_toResourcePath(t, n), r, i, s))).catch((e => {\n throw \"FirebaseError\" === e.name ? (e.code === D.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(D.UNKNOWN, e.toString());\n }));\n }\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ Lo(e, t, n, r, i) {\n return this.w_(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.Lo(e, __PRIVATE_toResourcePath(t, n), r, s, o, i))).catch((e => {\n throw \"FirebaseError\" === e.name ? (e.code === D.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(D.UNKNOWN, e.toString());\n }));\n }\n terminate() {\n this.y_ = !0, this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nclass __PRIVATE_OnlineStateTracker {\n constructor(e, t) {\n this.asyncQueue = e, this.onlineStateHandler = t, \n /** The current OnlineState. */\n this.state = \"Unknown\" /* OnlineState.Unknown */ , \n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n this.S_ = 0, \n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n this.b_ = null, \n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n this.D_ = !0;\n }\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */ v_() {\n 0 === this.S_ && (this.C_(\"Unknown\" /* OnlineState.Unknown */), this.b_ = this.asyncQueue.enqueueAfterDelay(\"online_state_timeout\" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this.b_ = null, \n this.F_(\"Backend didn't respond within 10 seconds.\"), this.C_(\"Offline\" /* OnlineState.Offline */), \n Promise.resolve()))));\n }\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */ M_(e) {\n \"Online\" /* OnlineState.Online */ === this.state ? this.C_(\"Unknown\" /* OnlineState.Unknown */) : (this.S_++, \n this.S_ >= 1 && (this.x_(), this.F_(`Connection failed 1 times. Most recent error: ${e.toString()}`), \n this.C_(\"Offline\" /* OnlineState.Offline */)));\n }\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */ set(e) {\n this.x_(), this.S_ = 0, \"Online\" /* OnlineState.Online */ === e && (\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.D_ = !1), this.C_(e);\n }\n C_(e) {\n e !== this.state && (this.state = e, this.onlineStateHandler(e));\n }\n F_(e) {\n const t = `Could not reach Cloud Firestore backend. ${e}\\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;\n this.D_ ? (__PRIVATE_logError(t), this.D_ = !1) : __PRIVATE_logDebug(\"OnlineStateTracker\", t);\n }\n x_() {\n null !== this.b_ && (this.b_.cancel(), this.b_ = null);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_RemoteStoreImpl {\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n e, \n /** The client-side proxy for interacting with the backend. */\n t, n, r, i) {\n this.localStore = e, this.datastore = t, this.asyncQueue = n, this.remoteSyncer = {}, \n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n this.O_ = [], \n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n this.N_ = new Map, \n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n this.L_ = new Set, \n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n this.B_ = [], this.k_ = i, this.k_._o((e => {\n n.enqueueAndForget((async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(\"RemoteStore\", \"Restarting streams for network reachability change.\"), \n await async function __PRIVATE_restartNetwork(e) {\n const t = __PRIVATE_debugCast(e);\n t.L_.add(4 /* OfflineCause.ConnectivityChange */), await __PRIVATE_disableNetworkInternal(t), \n t.q_.set(\"Unknown\" /* OnlineState.Unknown */), t.L_.delete(4 /* OfflineCause.ConnectivityChange */), \n await __PRIVATE_enableNetworkInternal(t);\n }(this));\n }));\n })), this.q_ = new __PRIVATE_OnlineStateTracker(n, r);\n }\n}\n\nasync function __PRIVATE_enableNetworkInternal(e) {\n if (__PRIVATE_canUseNetwork(e)) for (const t of e.B_) await t(/* enabled= */ !0);\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */ async function __PRIVATE_disableNetworkInternal(e) {\n for (const t of e.B_) await t(/* enabled= */ !1);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nfunction __PRIVATE_remoteStoreListen(e, t) {\n const n = __PRIVATE_debugCast(e);\n n.N_.has(t.targetId) || (\n // Mark this as something the client is currently listening for.\n n.N_.set(t.targetId, t), __PRIVATE_shouldStartWatchStream(n) ? \n // The listen will be sent in onWatchStreamOpen\n __PRIVATE_startWatchStream(n) : __PRIVATE_ensureWatchStream(n).r_() && __PRIVATE_sendWatchRequest(n, t));\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */ function __PRIVATE_remoteStoreUnlisten(e, t) {\n const n = __PRIVATE_debugCast(e), r = __PRIVATE_ensureWatchStream(n);\n n.N_.delete(t), r.r_() && __PRIVATE_sendUnwatchRequest(n, t), 0 === n.N_.size && (r.r_() ? r.o_() : __PRIVATE_canUseNetwork(n) && \n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n n.q_.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */ function __PRIVATE_sendWatchRequest(e, t) {\n if (e.Q_.xe(t.targetId), t.resumeToken.approximateByteSize() > 0 || t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n const n = e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;\n t = t.withExpectedCount(n);\n }\n __PRIVATE_ensureWatchStream(e).A_(t);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */ function __PRIVATE_sendUnwatchRequest(e, t) {\n e.Q_.xe(t), __PRIVATE_ensureWatchStream(e).R_(t);\n}\n\nfunction __PRIVATE_startWatchStream(e) {\n e.Q_ = new __PRIVATE_WatchChangeAggregator({\n getRemoteKeysForTarget: t => e.remoteSyncer.getRemoteKeysForTarget(t),\n ot: t => e.N_.get(t) || null,\n tt: () => e.datastore.serializer.databaseId\n }), __PRIVATE_ensureWatchStream(e).start(), e.q_.v_();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */ function __PRIVATE_shouldStartWatchStream(e) {\n return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWatchStream(e).n_() && e.N_.size > 0;\n}\n\nfunction __PRIVATE_canUseNetwork(e) {\n return 0 === __PRIVATE_debugCast(e).L_.size;\n}\n\nfunction __PRIVATE_cleanUpWatchStreamState(e) {\n e.Q_ = void 0;\n}\n\nasync function __PRIVATE_onWatchStreamConnected(e) {\n // Mark the client as online since we got a \"connected\" notification.\n e.q_.set(\"Online\" /* OnlineState.Online */);\n}\n\nasync function __PRIVATE_onWatchStreamOpen(e) {\n e.N_.forEach(((t, n) => {\n __PRIVATE_sendWatchRequest(e, t);\n }));\n}\n\nasync function __PRIVATE_onWatchStreamClose(e, t) {\n __PRIVATE_cleanUpWatchStreamState(e), \n // If we still need the watch stream, retry the connection.\n __PRIVATE_shouldStartWatchStream(e) ? (e.q_.M_(t), __PRIVATE_startWatchStream(e)) : \n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n e.q_.set(\"Unknown\" /* OnlineState.Unknown */);\n}\n\nasync function __PRIVATE_onWatchStreamChange(e, t, n) {\n if (\n // Mark the client as online since we got a message from the server\n e.q_.set(\"Online\" /* OnlineState.Online */), t instanceof __PRIVATE_WatchTargetChange && 2 /* WatchTargetChangeState.Removed */ === t.state && t.cause) \n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await \n /** Handles an error on a target */\n async function __PRIVATE_handleTargetError(e, t) {\n const n = t.cause;\n for (const r of t.targetIds) \n // A watched target might have been removed already.\n e.N_.has(r) && (await e.remoteSyncer.rejectListen(r, n), e.N_.delete(r), e.Q_.removeTarget(r));\n }\n /**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */ (e, t);\n } catch (n) {\n __PRIVATE_logDebug(\"RemoteStore\", \"Failed to remove targets %s: %s \", t.targetIds.join(\",\"), n), \n await __PRIVATE_disableNetworkUntilRecovery(e, n);\n } else if (t instanceof __PRIVATE_DocumentWatchChange ? e.Q_.Ke(t) : t instanceof __PRIVATE_ExistenceFilterChange ? e.Q_.He(t) : e.Q_.We(t), \n !n.isEqual(SnapshotVersion.min())) try {\n const t = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore);\n n.compareTo(t) >= 0 && \n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await \n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n function __PRIVATE_raiseWatchSnapshot(e, t) {\n const n = e.Q_.rt(t);\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n return n.targetChanges.forEach(((n, r) => {\n if (n.resumeToken.approximateByteSize() > 0) {\n const i = e.N_.get(r);\n // A watched target might have been removed already.\n i && e.N_.set(r, i.withResumeToken(n.resumeToken, t));\n }\n })), \n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n n.targetMismatches.forEach(((t, n) => {\n const r = e.N_.get(t);\n if (!r) \n // A watched target might have been removed already.\n return;\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n e.N_.set(t, r.withResumeToken(ByteString.EMPTY_BYTE_STRING, r.snapshotVersion)), \n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n __PRIVATE_sendUnwatchRequest(e, t);\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const i = new TargetData(r.target, t, n, r.sequenceNumber);\n __PRIVATE_sendWatchRequest(e, i);\n })), e.remoteSyncer.applyRemoteEvent(n);\n }(e, n);\n } catch (t) {\n __PRIVATE_logDebug(\"RemoteStore\", \"Failed to raise snapshot:\", t), await __PRIVATE_disableNetworkUntilRecovery(e, t);\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */ async function __PRIVATE_disableNetworkUntilRecovery(e, t, n) {\n if (!__PRIVATE_isIndexedDbTransactionError(t)) throw t;\n e.L_.add(1 /* OfflineCause.IndexedDbFailed */), \n // Disable network and raise offline snapshots\n await __PRIVATE_disableNetworkInternal(e), e.q_.set(\"Offline\" /* OnlineState.Offline */), \n n || (\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n n = () => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)), \n // Probe IndexedDB periodically and re-enable network\n e.asyncQueue.enqueueRetryable((async () => {\n __PRIVATE_logDebug(\"RemoteStore\", \"Retrying IndexedDB access\"), await n(), e.L_.delete(1 /* OfflineCause.IndexedDbFailed */), \n await __PRIVATE_enableNetworkInternal(e);\n }));\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */ function __PRIVATE_executeWithRecovery(e, t) {\n return t().catch((n => __PRIVATE_disableNetworkUntilRecovery(e, n, t)));\n}\n\nasync function __PRIVATE_fillWritePipeline(e) {\n const t = __PRIVATE_debugCast(e), n = __PRIVATE_ensureWriteStream(t);\n let r = t.O_.length > 0 ? t.O_[t.O_.length - 1].batchId : -1;\n for (;__PRIVATE_canAddToWritePipeline(t); ) try {\n const e = await __PRIVATE_localStoreGetNextMutationBatch(t.localStore, r);\n if (null === e) {\n 0 === t.O_.length && n.o_();\n break;\n }\n r = e.batchId, __PRIVATE_addToWritePipeline(t, e);\n } catch (e) {\n await __PRIVATE_disableNetworkUntilRecovery(t, e);\n }\n __PRIVATE_shouldStartWriteStream(t) && __PRIVATE_startWriteStream(t);\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */ function __PRIVATE_canAddToWritePipeline(e) {\n return __PRIVATE_canUseNetwork(e) && e.O_.length < 10;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */ function __PRIVATE_addToWritePipeline(e, t) {\n e.O_.push(t);\n const n = __PRIVATE_ensureWriteStream(e);\n n.r_() && n.V_ && n.m_(t.mutations);\n}\n\nfunction __PRIVATE_shouldStartWriteStream(e) {\n return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWriteStream(e).n_() && e.O_.length > 0;\n}\n\nfunction __PRIVATE_startWriteStream(e) {\n __PRIVATE_ensureWriteStream(e).start();\n}\n\nasync function __PRIVATE_onWriteStreamOpen(e) {\n __PRIVATE_ensureWriteStream(e).p_();\n}\n\nasync function __PRIVATE_onWriteHandshakeComplete(e) {\n const t = __PRIVATE_ensureWriteStream(e);\n // Send the write pipeline now that the stream is established.\n for (const n of e.O_) t.m_(n.mutations);\n}\n\nasync function __PRIVATE_onMutationResult(e, t, n) {\n const r = e.O_.shift(), i = MutationBatchResult.from(r, t, n);\n await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.applySuccessfulWrite(i))), \n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await __PRIVATE_fillWritePipeline(e);\n}\n\nasync function __PRIVATE_onWriteStreamClose(e, t) {\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n t && __PRIVATE_ensureWriteStream(e).V_ && \n // This error affects the actual write.\n await async function __PRIVATE_handleWriteError(e, t) {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (function __PRIVATE_isPermanentWriteError(e) {\n return __PRIVATE_isPermanentError(e) && e !== D.ABORTED;\n }(t.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const n = e.O_.shift();\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n __PRIVATE_ensureWriteStream(e).s_(), await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.rejectFailedWrite(n.batchId, t))), \n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await __PRIVATE_fillWritePipeline(e);\n }\n }(e, t), \n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n __PRIVATE_shouldStartWriteStream(e) && __PRIVATE_startWriteStream(e);\n}\n\nasync function __PRIVATE_remoteStoreHandleCredentialChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n n.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(\"RemoteStore\", \"RemoteStore received new credentials\");\n const r = __PRIVATE_canUseNetwork(n);\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n n.L_.add(3 /* OfflineCause.CredentialChange */), await __PRIVATE_disableNetworkInternal(n), \n r && \n // Don't set the network status to Unknown if we are offline.\n n.q_.set(\"Unknown\" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(t), \n n.L_.delete(3 /* OfflineCause.CredentialChange */), await __PRIVATE_enableNetworkInternal(n);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */ async function __PRIVATE_remoteStoreApplyPrimaryState(e, t) {\n const n = __PRIVATE_debugCast(e);\n t ? (n.L_.delete(2 /* OfflineCause.IsSecondary */), await __PRIVATE_enableNetworkInternal(n)) : t || (n.L_.add(2 /* OfflineCause.IsSecondary */), \n await __PRIVATE_disableNetworkInternal(n), n.q_.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function __PRIVATE_ensureWatchStream(e) {\n return e.K_ || (\n // Create stream (but note that it is not started yet).\n e.K_ = function __PRIVATE_newPersistentWatchStream(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n return r.w_(), new __PRIVATE_PersistentListenStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);\n }\n /**\n * @license\n * Copyright 2018 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 */ (e.datastore, e.asyncQueue, {\n Eo: __PRIVATE_onWatchStreamConnected.bind(null, e),\n Ro: __PRIVATE_onWatchStreamOpen.bind(null, e),\n mo: __PRIVATE_onWatchStreamClose.bind(null, e),\n d_: __PRIVATE_onWatchStreamChange.bind(null, e)\n }), e.B_.push((async t => {\n t ? (e.K_.s_(), __PRIVATE_shouldStartWatchStream(e) ? __PRIVATE_startWatchStream(e) : e.q_.set(\"Unknown\" /* OnlineState.Unknown */)) : (await e.K_.stop(), \n __PRIVATE_cleanUpWatchStreamState(e));\n }))), e.K_;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function __PRIVATE_ensureWriteStream(e) {\n return e.U_ || (\n // Create stream (but note that it is not started yet).\n e.U_ = function __PRIVATE_newPersistentWriteStream(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n return r.w_(), new __PRIVATE_PersistentWriteStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);\n }(e.datastore, e.asyncQueue, {\n Eo: () => Promise.resolve(),\n Ro: __PRIVATE_onWriteStreamOpen.bind(null, e),\n mo: __PRIVATE_onWriteStreamClose.bind(null, e),\n f_: __PRIVATE_onWriteHandshakeComplete.bind(null, e),\n g_: __PRIVATE_onMutationResult.bind(null, e)\n }), e.B_.push((async t => {\n t ? (e.U_.s_(), \n // This will start the write stream if necessary.\n await __PRIVATE_fillWritePipeline(e)) : (await e.U_.stop(), e.O_.length > 0 && (__PRIVATE_logDebug(\"RemoteStore\", `Stopping write stream with ${e.O_.length} pending writes`), \n e.O_ = []));\n }))), e.U_;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nclass DelayedOperation {\n constructor(e, t, n, r, i) {\n this.asyncQueue = e, this.timerId = t, this.targetTimeMs = n, this.op = r, this.removalCallback = i, \n this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), \n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch((e => {}));\n }\n get promise() {\n return this.deferred.promise;\n }\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */ static createAndSchedule(e, t, n, r, i) {\n const s = Date.now() + n, o = new DelayedOperation(e, t, s, r, i);\n return o.start(n), o;\n }\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */ start(e) {\n this.timerHandle = setTimeout((() => this.handleDelayElapsed()), e);\n }\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */ skipDelay() {\n return this.handleDelayElapsed();\n }\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */ cancel(e) {\n null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(D.CANCELLED, \"Operation cancelled\" + (e ? \": \" + e : \"\"))));\n }\n handleDelayElapsed() {\n this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), \n this.op().then((e => this.deferred.resolve(e)))) : Promise.resolve()));\n }\n clearTimeout() {\n null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), \n this.timerHandle = null);\n }\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */ function __PRIVATE_wrapInUserErrorIfRecoverable(e, t) {\n if (__PRIVATE_logError(\"AsyncQueue\", `${t}: ${e}`), __PRIVATE_isIndexedDbTransactionError(e)) return new FirestoreError(D.UNAVAILABLE, `${t}: ${e}`);\n throw e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */ class DocumentSet {\n /** The default ordering is by key if the comparator is omitted */\n constructor(e) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n this.comparator = e ? (t, n) => e(t, n) || DocumentKey.comparator(t.key, n.key) : (e, t) => DocumentKey.comparator(e.key, t.key), \n this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */ static emptySet(e) {\n return new DocumentSet(e.comparator);\n }\n has(e) {\n return null != this.keyedMap.get(e);\n }\n get(e) {\n return this.keyedMap.get(e);\n }\n first() {\n return this.sortedSet.minKey();\n }\n last() {\n return this.sortedSet.maxKey();\n }\n isEmpty() {\n return this.sortedSet.isEmpty();\n }\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */ indexOf(e) {\n const t = this.keyedMap.get(e);\n return t ? this.sortedSet.indexOf(t) : -1;\n }\n get size() {\n return this.sortedSet.size;\n }\n /** Iterates documents in order defined by \"comparator\" */ forEach(e) {\n this.sortedSet.inorderTraversal(((t, n) => (e(t), !1)));\n }\n /** Inserts or updates a document with the same key */ add(e) {\n // First remove the element if we have it.\n const t = this.delete(e.key);\n return t.copy(t.keyedMap.insert(e.key, e), t.sortedSet.insert(e, null));\n }\n /** Deletes a document with a given key */ delete(e) {\n const t = this.get(e);\n return t ? this.copy(this.keyedMap.remove(e), this.sortedSet.remove(t)) : this;\n }\n isEqual(e) {\n if (!(e instanceof DocumentSet)) return !1;\n if (this.size !== e.size) return !1;\n const t = this.sortedSet.getIterator(), n = e.sortedSet.getIterator();\n for (;t.hasNext(); ) {\n const e = t.getNext().key, r = n.getNext().key;\n if (!e.isEqual(r)) return !1;\n }\n return !0;\n }\n toString() {\n const e = [];\n return this.forEach((t => {\n e.push(t.toString());\n })), 0 === e.length ? \"DocumentSet ()\" : \"DocumentSet (\\n \" + e.join(\" \\n\") + \"\\n)\";\n }\n copy(e, t) {\n const n = new DocumentSet;\n return n.comparator = this.comparator, n.keyedMap = e, n.sortedSet = t, n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */ class __PRIVATE_DocumentChangeSet {\n constructor() {\n this.W_ = new SortedMap(DocumentKey.comparator);\n }\n track(e) {\n const t = e.doc.key, n = this.W_.get(t);\n n ? \n // Merge the new change with the existing change.\n 0 /* ChangeType.Added */ !== e.type && 3 /* ChangeType.Metadata */ === n.type ? this.W_ = this.W_.insert(t, e) : 3 /* ChangeType.Metadata */ === e.type && 1 /* ChangeType.Removed */ !== n.type ? this.W_ = this.W_.insert(t, {\n type: n.type,\n doc: e.doc\n }) : 2 /* ChangeType.Modified */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.W_ = this.W_.insert(t, {\n type: 2 /* ChangeType.Modified */ ,\n doc: e.doc\n }) : 2 /* ChangeType.Modified */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.W_ = this.W_.insert(t, {\n type: 0 /* ChangeType.Added */ ,\n doc: e.doc\n }) : 1 /* ChangeType.Removed */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.W_ = this.W_.remove(t) : 1 /* ChangeType.Removed */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.W_ = this.W_.insert(t, {\n type: 1 /* ChangeType.Removed */ ,\n doc: n.doc\n }) : 0 /* ChangeType.Added */ === e.type && 1 /* ChangeType.Removed */ === n.type ? this.W_ = this.W_.insert(t, {\n type: 2 /* ChangeType.Modified */ ,\n doc: e.doc\n }) : \n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail() : this.W_ = this.W_.insert(t, e);\n }\n G_() {\n const e = [];\n return this.W_.inorderTraversal(((t, n) => {\n e.push(n);\n })), e;\n }\n}\n\nclass ViewSnapshot {\n constructor(e, t, n, r, i, s, o, _, a) {\n this.query = e, this.docs = t, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i, \n this.fromCache = s, this.syncStateChanged = o, this.excludesMetadataChanges = _, \n this.hasCachedResults = a;\n }\n /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(e, t, n, r, i) {\n const s = [];\n return t.forEach((e => {\n s.push({\n type: 0 /* ChangeType.Added */ ,\n doc: e\n });\n })), new ViewSnapshot(e, t, DocumentSet.emptySet(t), s, n, r, \n /* syncStateChanged= */ !0, \n /* excludesMetadataChanges= */ !1, i);\n }\n get hasPendingWrites() {\n return !this.mutatedKeys.isEmpty();\n }\n isEqual(e) {\n if (!(this.fromCache === e.fromCache && this.hasCachedResults === e.hasCachedResults && this.syncStateChanged === e.syncStateChanged && this.mutatedKeys.isEqual(e.mutatedKeys) && __PRIVATE_queryEquals(this.query, e.query) && this.docs.isEqual(e.docs) && this.oldDocs.isEqual(e.oldDocs))) return !1;\n const t = this.docChanges, n = e.docChanges;\n if (t.length !== n.length) return !1;\n for (let e = 0; e < t.length; e++) if (t[e].type !== n[e].type || !t[e].doc.isEqual(n[e].doc)) return !1;\n return !0;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */ class __PRIVATE_QueryListenersInfo {\n constructor() {\n this.z_ = void 0, this.j_ = [];\n }\n // Helper methods that checks if the query has listeners that listening to remote store\n H_() {\n return this.j_.some((e => e.J_()));\n }\n}\n\nclass __PRIVATE_EventManagerImpl {\n constructor() {\n this.queries = __PRIVATE_newQueriesObjectMap(), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.Y_ = new Set;\n }\n terminate() {\n !function __PRIVATE_errorAllTargets(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.queries;\n // Prevent further access by clearing ObjectMap.\n n.queries = __PRIVATE_newQueriesObjectMap(), r.forEach(((e, n) => {\n for (const e of n.j_) e.onError(t);\n }));\n }\n // Call all global snapshot listeners that have been set.\n (this, new FirestoreError(D.ABORTED, \"Firestore shutting down\"));\n }\n}\n\nfunction __PRIVATE_newQueriesObjectMap() {\n return new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals);\n}\n\nasync function __PRIVATE_eventManagerListen(e, t) {\n const n = __PRIVATE_debugCast(e);\n let r = 3 /* ListenerSetupAction.NoActionRequired */;\n const i = t.query;\n let s = n.queries.get(i);\n s ? !s.H_() && t.J_() && (\n // Query has been listening to local cache, and tries to add a new listener sourced from watch.\n r = 2 /* ListenerSetupAction.RequireWatchConnectionOnly */) : (s = new __PRIVATE_QueryListenersInfo, \n r = t.J_() ? 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : 1 /* ListenerSetupAction.InitializeLocalListenOnly */);\n try {\n switch (r) {\n case 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ :\n s.z_ = await n.onListen(i, \n /** enableRemoteListen= */ !0);\n break;\n\n case 1 /* ListenerSetupAction.InitializeLocalListenOnly */ :\n s.z_ = await n.onListen(i, \n /** enableRemoteListen= */ !1);\n break;\n\n case 2 /* ListenerSetupAction.RequireWatchConnectionOnly */ :\n await n.onFirstRemoteStoreListen(i);\n }\n } catch (e) {\n const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Initialization of query '${__PRIVATE_stringifyQuery(t.query)}' failed`);\n return void t.onError(n);\n }\n if (n.queries.set(i, s), s.j_.push(t), \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n t.Z_(n.onlineState), s.z_) {\n t.X_(s.z_) && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n }\n}\n\nasync function __PRIVATE_eventManagerUnlisten(e, t) {\n const n = __PRIVATE_debugCast(e), r = t.query;\n let i = 3 /* ListenerRemovalAction.NoActionRequired */;\n const s = n.queries.get(r);\n if (s) {\n const e = s.j_.indexOf(t);\n e >= 0 && (s.j_.splice(e, 1), 0 === s.j_.length ? i = t.J_() ? 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : !s.H_() && t.J_() && (\n // The removed listener is the last one that sourced from watch.\n i = 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */));\n }\n switch (i) {\n case 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ :\n return n.queries.delete(r), n.onUnlisten(r, \n /** disableRemoteListen= */ !0);\n\n case 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ :\n return n.queries.delete(r), n.onUnlisten(r, \n /** disableRemoteListen= */ !1);\n\n case 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */ :\n return n.onLastRemoteStoreUnlisten(r);\n\n default:\n return;\n }\n}\n\nfunction __PRIVATE_eventManagerOnWatchChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n let r = !1;\n for (const e of t) {\n const t = e.query, i = n.queries.get(t);\n if (i) {\n for (const t of i.j_) t.X_(e) && (r = !0);\n i.z_ = e;\n }\n }\n r && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n}\n\nfunction __PRIVATE_eventManagerOnWatchError(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = r.queries.get(t);\n if (i) for (const e of i.j_) e.onError(n);\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n r.queries.delete(t);\n}\n\nfunction __PRIVATE_raiseSnapshotsInSyncEvent(e) {\n e.Y_.forEach((e => {\n e.next();\n }));\n}\n\nvar pe, ye;\n\n/** Listen to both cache and server changes */\n(ye = pe || (pe = {})).ea = \"default\", \n/** Listen to changes in cache only */\nye.Cache = \"cache\";\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nclass __PRIVATE_QueryListener {\n constructor(e, t, n) {\n this.query = e, this.ta = t, \n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n this.na = !1, this.ra = null, this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.options = n || {};\n }\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */ X_(e) {\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const t = [];\n for (const n of e.docChanges) 3 /* ChangeType.Metadata */ !== n.type && t.push(n);\n e = new ViewSnapshot(e.query, e.docs, e.oldDocs, t, e.mutatedKeys, e.fromCache, e.syncStateChanged, \n /* excludesMetadataChanges= */ !0, e.hasCachedResults);\n }\n let t = !1;\n return this.na ? this.ia(e) && (this.ta.next(e), t = !0) : this.sa(e, this.onlineState) && (this.oa(e), \n t = !0), this.ra = e, t;\n }\n onError(e) {\n this.ta.error(e);\n }\n /** Returns whether a snapshot was raised. */ Z_(e) {\n this.onlineState = e;\n let t = !1;\n return this.ra && !this.na && this.sa(this.ra, e) && (this.oa(this.ra), t = !0), \n t;\n }\n sa(e, t) {\n // Always raise the first event when we're synced\n if (!e.fromCache) return !0;\n // Always raise event if listening to cache\n if (!this.J_()) return !0;\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const n = \"Offline\" /* OnlineState.Offline */ !== t;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n return (!this.options._a || !n) && (!e.docs.isEmpty() || e.hasCachedResults || \"Offline\" /* OnlineState.Offline */ === t);\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n }\n ia(e) {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (e.docChanges.length > 0) return !0;\n const t = this.ra && this.ra.hasPendingWrites !== e.hasPendingWrites;\n return !(!e.syncStateChanged && !t) && !0 === this.options.includeMetadataChanges;\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n }\n oa(e) {\n e = ViewSnapshot.fromInitialDocuments(e.query, e.docs, e.mutatedKeys, e.fromCache, e.hasCachedResults), \n this.na = !0, this.ta.next(e);\n }\n J_() {\n return this.options.source !== pe.Cache;\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/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */ class __PRIVATE_SizedBundleElement {\n constructor(e, \n // How many bytes this element takes to store in the bundle.\n t) {\n this.aa = e, this.byteLength = t;\n }\n ua() {\n return \"metadata\" in this.aa;\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/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */ class __PRIVATE_BundleConverterImpl {\n constructor(e) {\n this.serializer = e;\n }\n Es(e) {\n return fromName(this.serializer, e);\n }\n /**\n * Converts a BundleDocument to a MutableDocument.\n */ ds(e) {\n return e.metadata.exists ? __PRIVATE_fromDocument(this.serializer, e.document, !1) : MutableDocument.newNoDocument(this.Es(e.metadata.name), this.As(e.metadata.readTime));\n }\n As(e) {\n return __PRIVATE_fromVersion(e);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */ class __PRIVATE_BundleLoader {\n constructor(e, t, n) {\n this.ca = e, this.localStore = t, this.serializer = n, \n /** Batched queries to be saved into storage */\n this.queries = [], \n /** Batched documents to be saved into storage */\n this.documents = [], \n /** The collection groups affected by this bundle. */\n this.collectionGroups = new Set, this.progress = __PRIVATE_bundleInitialProgress(e);\n }\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */ la(e) {\n this.progress.bytesLoaded += e.byteLength;\n let t = this.progress.documentsLoaded;\n if (e.aa.namedQuery) this.queries.push(e.aa.namedQuery); else if (e.aa.documentMetadata) {\n this.documents.push({\n metadata: e.aa.documentMetadata\n }), e.aa.documentMetadata.exists || ++t;\n const n = ResourcePath.fromString(e.aa.documentMetadata.name);\n this.collectionGroups.add(n.get(n.length - 2));\n } else e.aa.document && (this.documents[this.documents.length - 1].document = e.aa.document, \n ++t);\n return t !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t, \n Object.assign({}, this.progress)) : null;\n }\n ha(e) {\n const t = new Map, n = new __PRIVATE_BundleConverterImpl(this.serializer);\n for (const r of e) if (r.metadata.queries) {\n const e = n.Es(r.metadata.name);\n for (const n of r.metadata.queries) {\n const r = (t.get(n) || __PRIVATE_documentKeySet()).add(e);\n t.set(n, r);\n }\n }\n return t;\n }\n /**\n * Update the progress to 'Success' and return the updated progress.\n */ async complete() {\n const e = await __PRIVATE_localStoreApplyBundledDocuments(this.localStore, new __PRIVATE_BundleConverterImpl(this.serializer), this.documents, this.ca.id), t = this.ha(this.documents);\n for (const e of this.queries) await __PRIVATE_localStoreSaveNamedQuery(this.localStore, e, t.get(e.name));\n return this.progress.taskState = \"Success\", {\n progress: this.progress,\n Pa: this.collectionGroups,\n Ia: e\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */ function __PRIVATE_bundleInitialProgress(e) {\n return {\n taskState: \"Running\",\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: e.totalDocuments,\n totalBytes: e.totalBytes\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass __PRIVATE_AddedLimboDocument {\n constructor(e) {\n this.key = e;\n }\n}\n\nclass __PRIVATE_RemovedLimboDocument {\n constructor(e) {\n this.key = e;\n }\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */ class __PRIVATE_View {\n constructor(e, \n /** Documents included in the remote target */\n t) {\n this.query = e, this.Ta = t, this.Ea = null, this.hasCachedResults = !1, \n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n this.current = !1, \n /** Documents in the view but not in the remote target */\n this.da = __PRIVATE_documentKeySet(), \n /** Document Keys that have local changes */\n this.mutatedKeys = __PRIVATE_documentKeySet(), this.Aa = __PRIVATE_newQueryComparator(e), \n this.Ra = new DocumentSet(this.Aa);\n }\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */ get Va() {\n return this.Ta;\n }\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */ ma(e, t) {\n const n = t ? t.fa : new __PRIVATE_DocumentChangeSet, r = t ? t.Ra : this.Ra;\n let i = t ? t.mutatedKeys : this.mutatedKeys, s = r, o = !1;\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const _ = \"F\" /* LimitType.First */ === this.query.limitType && r.size === this.query.limit ? r.last() : null, a = \"L\" /* LimitType.Last */ === this.query.limitType && r.size === this.query.limit ? r.first() : null;\n // Drop documents out to meet limit/limitToLast requirement.\n if (e.inorderTraversal(((e, t) => {\n const u = r.get(e), c = __PRIVATE_queryMatches(this.query, t) ? t : null, l = !!u && this.mutatedKeys.has(u.key), h = !!c && (c.hasLocalMutations || \n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n this.mutatedKeys.has(c.key) && c.hasCommittedMutations);\n let P = !1;\n // Calculate change\n if (u && c) {\n u.data.isEqual(c.data) ? l !== h && (n.track({\n type: 3 /* ChangeType.Metadata */ ,\n doc: c\n }), P = !0) : this.ga(u, c) || (n.track({\n type: 2 /* ChangeType.Modified */ ,\n doc: c\n }), P = !0, (_ && this.Aa(c, _) > 0 || a && this.Aa(c, a) < 0) && (\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n o = !0));\n } else !u && c ? (n.track({\n type: 0 /* ChangeType.Added */ ,\n doc: c\n }), P = !0) : u && !c && (n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: u\n }), P = !0, (_ || a) && (\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n o = !0));\n P && (c ? (s = s.add(c), i = h ? i.add(e) : i.delete(e)) : (s = s.delete(e), i = i.delete(e)));\n })), null !== this.query.limit) for (;s.size > this.query.limit; ) {\n const e = \"F\" /* LimitType.First */ === this.query.limitType ? s.last() : s.first();\n s = s.delete(e.key), i = i.delete(e.key), n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: e\n });\n }\n return {\n Ra: s,\n fa: n,\n ns: o,\n mutatedKeys: i\n };\n }\n ga(e, t) {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return e.hasLocalMutations && t.hasCommittedMutations && !t.hasLocalMutations;\n }\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(e, t, n, r) {\n const i = this.Ra;\n this.Ra = e.Ra, this.mutatedKeys = e.mutatedKeys;\n // Sort changes based on type and query comparator\n const s = e.fa.G_();\n s.sort(((e, t) => function __PRIVATE_compareChangeType(e, t) {\n const order = e => {\n switch (e) {\n case 0 /* ChangeType.Added */ :\n return 1;\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n\n case 1 /* ChangeType.Removed */ :\n return 0;\n\n default:\n return fail();\n }\n };\n return order(e) - order(t);\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 */ (e.type, t.type) || this.Aa(e.doc, t.doc))), this.pa(n), r = null != r && r;\n const o = t && !r ? this.ya() : [], _ = 0 === this.da.size && this.current && !r ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , a = _ !== this.Ea;\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n if (this.Ea = _, 0 !== s.length || a) {\n return {\n snapshot: new ViewSnapshot(this.query, e.Ra, i, s, e.mutatedKeys, 0 /* SyncState.Local */ === _, a, \n /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),\n wa: o\n };\n }\n // no changes\n return {\n wa: o\n };\n }\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */ Z_(e) {\n return this.current && \"Offline\" /* OnlineState.Offline */ === e ? (\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = !1, this.applyChanges({\n Ra: this.Ra,\n fa: new __PRIVATE_DocumentChangeSet,\n mutatedKeys: this.mutatedKeys,\n ns: !1\n }, \n /* limboResolutionEnabled= */ !1)) : {\n wa: []\n };\n }\n /**\n * Returns whether the doc for the given key should be in limbo.\n */ Sa(e) {\n // If the remote end says it's part of this query, it's not in limbo.\n return !this.Ta.has(e) && (\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n !!this.Ra.has(e) && !this.Ra.get(e).hasLocalMutations);\n }\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */ pa(e) {\n e && (e.addedDocuments.forEach((e => this.Ta = this.Ta.add(e))), e.modifiedDocuments.forEach((e => {})), \n e.removedDocuments.forEach((e => this.Ta = this.Ta.delete(e))), this.current = e.current);\n }\n ya() {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) return [];\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const e = this.da;\n this.da = __PRIVATE_documentKeySet(), this.Ra.forEach((e => {\n this.Sa(e.key) && (this.da = this.da.add(e.key));\n }));\n // Diff the new limbo docs with the old limbo docs.\n const t = [];\n return e.forEach((e => {\n this.da.has(e) || t.push(new __PRIVATE_RemovedLimboDocument(e));\n })), this.da.forEach((n => {\n e.has(n) || t.push(new __PRIVATE_AddedLimboDocument(n));\n })), t;\n }\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n ba(e) {\n this.Ta = e.Ts, this.da = __PRIVATE_documentKeySet();\n const t = this.ma(e.documents);\n return this.applyChanges(t, /* limboResolutionEnabled= */ !0);\n }\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n Da() {\n return ViewSnapshot.fromInitialDocuments(this.query, this.Ra, this.mutatedKeys, 0 /* SyncState.Local */ === this.Ea, this.hasCachedResults);\n }\n}\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass __PRIVATE_QueryView {\n constructor(\n /**\n * The query itself.\n */\n e, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n t, \n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n n) {\n this.query = e, this.targetId = t, this.view = n;\n }\n}\n\n/** Tracks a limbo resolution. */ class LimboResolution {\n constructor(e) {\n this.key = e, \n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n this.va = !1;\n }\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */ class __PRIVATE_SyncEngineImpl {\n constructor(e, t, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n r, i, s) {\n this.localStore = e, this.remoteStore = t, this.eventManager = n, this.sharedClientState = r, \n this.currentUser = i, this.maxConcurrentLimboResolutions = s, this.Ca = {}, this.Fa = new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals), \n this.Ma = new Map, \n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n this.xa = new Set, \n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n this.Oa = new SortedMap(DocumentKey.comparator), \n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n this.Na = new Map, this.La = new __PRIVATE_ReferenceSet, \n /** Stores user completion handlers, indexed by User and BatchId. */\n this.Ba = {}, \n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n this.ka = new Map, this.qa = __PRIVATE_TargetIdGenerator.kn(), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n this.Qa = void 0;\n }\n get isPrimaryClient() {\n return !0 === this.Qa;\n }\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nasync function __PRIVATE_syncEngineListen(e, t, n = !0) {\n const r = __PRIVATE_ensureWatchCallbacks(e);\n let i;\n const s = r.Fa.get(t);\n return s ? (\n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n r.sharedClientState.addLocalQueryTarget(s.targetId), i = s.view.Da()) : i = await __PRIVATE_allocateTargetAndMaybeListen(r, t, n, \n /** shouldInitializeView= */ !0), i;\n}\n\n/** Query has been listening to the cache, and tries to initiate the remote store listen */ async function __PRIVATE_triggerRemoteStoreListen(e, t) {\n const n = __PRIVATE_ensureWatchCallbacks(e);\n await __PRIVATE_allocateTargetAndMaybeListen(n, t, \n /** shouldListenToRemote= */ !0, \n /** shouldInitializeView= */ !1);\n}\n\nasync function __PRIVATE_allocateTargetAndMaybeListen(e, t, n, r) {\n const i = await __PRIVATE_localStoreAllocateTarget(e.localStore, __PRIVATE_queryToTarget(t)), s = i.targetId, o = e.sharedClientState.addLocalQueryTarget(s, n);\n let _;\n return r && (_ = await __PRIVATE_initializeViewAndComputeSnapshot(e, t, s, \"current\" === o, i.resumeToken)), \n e.isPrimaryClient && n && __PRIVATE_remoteStoreListen(e.remoteStore, i), _;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */ async function __PRIVATE_initializeViewAndComputeSnapshot(e, t, n, r, i) {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n e.Ka = (t, n, r) => async function __PRIVATE_applyDocChanges(e, t, n, r) {\n let i = t.view.ma(n);\n i.ns && (\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n i = await __PRIVATE_localStoreExecuteQuery(e.localStore, t.query, \n /* usePreviousResults= */ !1).then((({documents: e}) => t.view.ma(e, i))));\n const s = r && r.targetChanges.get(t.targetId), o = r && null != r.targetMismatches.get(t.targetId), _ = t.view.applyChanges(i, \n /* limboResolutionEnabled= */ e.isPrimaryClient, s, o);\n return __PRIVATE_updateTrackedLimbos(e, t.targetId, _.wa), _.snapshot;\n }(e, t, n, r);\n const s = await __PRIVATE_localStoreExecuteQuery(e.localStore, t, \n /* usePreviousResults= */ !0), o = new __PRIVATE_View(t, s.Ts), _ = o.ma(s.documents), a = TargetChange.createSynthesizedTargetChangeForCurrentChange(n, r && \"Offline\" /* OnlineState.Offline */ !== e.onlineState, i), u = o.applyChanges(_, \n /* limboResolutionEnabled= */ e.isPrimaryClient, a);\n __PRIVATE_updateTrackedLimbos(e, n, u.wa);\n const c = new __PRIVATE_QueryView(t, n, o);\n return e.Fa.set(t, c), e.Ma.has(n) ? e.Ma.get(n).push(t) : e.Ma.set(n, [ t ]), u.snapshot;\n}\n\n/** Stops listening to the query. */ async function __PRIVATE_syncEngineUnlisten(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = r.Fa.get(t), s = r.Ma.get(i.targetId);\n if (s.length > 1) return r.Ma.set(i.targetId, s.filter((e => !__PRIVATE_queryEquals(e, t)))), \n void r.Fa.delete(t);\n // No other queries are mapped to the target, clean up the query and the target.\n if (r.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n r.sharedClientState.removeLocalQueryTarget(i.targetId);\n r.sharedClientState.isActiveQueryTarget(i.targetId) || await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, \n /*keepPersistedTargetData=*/ !1).then((() => {\n r.sharedClientState.clearQueryState(i.targetId), n && __PRIVATE_remoteStoreUnlisten(r.remoteStore, i.targetId), \n __PRIVATE_removeAndCleanupTarget(r, i.targetId);\n })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n } else __PRIVATE_removeAndCleanupTarget(r, i.targetId), await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, \n /*keepPersistedTargetData=*/ !0);\n}\n\n/** Unlistens to the remote store while still listening to the cache. */ async function __PRIVATE_triggerRemoteStoreUnlisten(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.Fa.get(t), i = n.Ma.get(r.targetId);\n n.isPrimaryClient && 1 === i.length && (\n // PORTING NOTE: Unregister the target ID with local Firestore client as\n // watch target.\n n.sharedClientState.removeLocalQueryTarget(r.targetId), __PRIVATE_remoteStoreUnlisten(n.remoteStore, r.targetId));\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */ async function __PRIVATE_syncEngineWrite(e, t, n) {\n const r = __PRIVATE_syncEngineEnsureWriteCallbacks(e);\n try {\n const e = await function __PRIVATE_localStoreWriteLocally(e, t) {\n const n = __PRIVATE_debugCast(e), r = Timestamp.now(), i = t.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet());\n let s, o;\n return n.persistence.runTransaction(\"Locally write mutations\", \"readwrite\", (e => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();\n return n.cs.getEntries(e, i).next((e => {\n _ = e, _.forEach(((e, t) => {\n t.isValidDocument() || (a = a.add(e));\n }));\n })).next((() => n.localDocuments.getOverlayedDocuments(e, _))).next((i => {\n s = i;\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const o = [];\n for (const e of t) {\n const t = __PRIVATE_mutationExtractBaseValue(e, s.get(e.key).overlayedDocument);\n null != t && \n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n o.push(new __PRIVATE_PatchMutation(e.key, t, __PRIVATE_extractFieldMask(t.value.mapValue), Precondition.exists(!0)));\n }\n return n.mutationQueue.addMutationBatch(e, r, o, t);\n })).next((t => {\n o = t;\n const r = t.applyToLocalDocumentSet(s, a);\n return n.documentOverlayCache.saveOverlays(e, t.batchId, r);\n }));\n })).then((() => ({\n batchId: o.batchId,\n changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s)\n })));\n }(r.localStore, t);\n r.sharedClientState.addPendingMutation(e.batchId), function __PRIVATE_addMutationCallback(e, t, n) {\n let r = e.Ba[e.currentUser.toKey()];\n r || (r = new SortedMap(__PRIVATE_primitiveComparator));\n r = r.insert(t, n), e.Ba[e.currentUser.toKey()] = r;\n }\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */ (r, e.batchId, n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e.changes), \n await __PRIVATE_fillWritePipeline(r.remoteStore);\n } catch (e) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const t = __PRIVATE_wrapInUserErrorIfRecoverable(e, \"Failed to persist write\");\n n.reject(t);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */ async function __PRIVATE_syncEngineApplyRemoteEvent(e, t) {\n const n = __PRIVATE_debugCast(e);\n try {\n const e = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n.localStore, t);\n // Update `receivedDocument` as appropriate for any limbo targets.\n t.targetChanges.forEach(((e, t) => {\n const r = n.Na.get(t);\n r && (\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n __PRIVATE_hardAssert(e.addedDocuments.size + e.modifiedDocuments.size + e.removedDocuments.size <= 1), \n e.addedDocuments.size > 0 ? r.va = !0 : e.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r.va) : e.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r.va), \n r.va = !1));\n })), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e, t);\n } catch (e) {\n await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */ function __PRIVATE_syncEngineApplyOnlineStateChange(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {\n const e = [];\n r.Fa.forEach(((n, r) => {\n const i = r.view.Z_(t);\n i.snapshot && e.push(i.snapshot);\n })), function __PRIVATE_eventManagerOnOnlineStateChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n n.onlineState = t;\n let r = !1;\n n.queries.forEach(((e, n) => {\n for (const e of n.j_) \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n e.Z_(t) && (r = !0);\n })), r && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n }(r.eventManager, t), e.length && r.Ca.d_(e), r.onlineState = t, r.isPrimaryClient && r.sharedClientState.setOnlineState(t);\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */ async function __PRIVATE_syncEngineRejectListen(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n // PORTING NOTE: Multi-tab only.\n r.sharedClientState.updateQueryState(t, \"rejected\", n);\n const i = r.Na.get(t), s = i && i.key;\n if (s) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let e = new SortedMap(DocumentKey.comparator);\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n e = e.insert(s, MutableDocument.newNoDocument(s, SnapshotVersion.min()));\n const n = __PRIVATE_documentKeySet().add(s), i = new RemoteEvent(SnapshotVersion.min(), \n /* targetChanges= */ new Map, \n /* targetMismatches= */ new SortedMap(__PRIVATE_primitiveComparator), e, n);\n await __PRIVATE_syncEngineApplyRemoteEvent(r, i), \n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n r.Oa = r.Oa.remove(s), r.Na.delete(t), __PRIVATE_pumpEnqueuedLimboResolutions(r);\n } else await __PRIVATE_localStoreReleaseTarget(r.localStore, t, \n /* keepPersistedTargetData */ !1).then((() => __PRIVATE_removeAndCleanupTarget(r, t, n))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n}\n\nasync function __PRIVATE_syncEngineApplySuccessfulWrite(e, t) {\n const n = __PRIVATE_debugCast(e), r = t.batch.batchId;\n try {\n const e = await __PRIVATE_localStoreAcknowledgeBatch(n.localStore, t);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n __PRIVATE_processUserCallback(n, r, /*error=*/ null), __PRIVATE_triggerPendingWritesCallbacks(n, r), \n n.sharedClientState.updateMutationState(r, \"acknowledged\"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e);\n } catch (e) {\n await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n }\n}\n\nasync function __PRIVATE_syncEngineRejectFailedWrite(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n try {\n const e = await function __PRIVATE_localStoreRejectBatch(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Reject batch\", \"readwrite-primary\", (e => {\n let r;\n return n.mutationQueue.lookupMutationBatch(e, t).next((t => (__PRIVATE_hardAssert(null !== t), \n r = t.keys(), n.mutationQueue.removeMutationBatch(e, t)))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, r))).next((() => n.localDocuments.getDocuments(e, r)));\n }));\n }\n /**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */ (r.localStore, t);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n __PRIVATE_processUserCallback(r, t, n), __PRIVATE_triggerPendingWritesCallbacks(r, t), \n r.sharedClientState.updateMutationState(t, \"rejected\", n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e);\n } catch (n) {\n await __PRIVATE_ignoreIfPrimaryLeaseLoss(n);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */ async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e, t) {\n const n = __PRIVATE_debugCast(e);\n __PRIVATE_canUseNetwork(n.remoteStore) || __PRIVATE_logDebug(\"SyncEngine\", \"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\");\n try {\n const e = await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e) {\n const t = __PRIVATE_debugCast(e);\n return t.persistence.runTransaction(\"Get highest unacknowledged batch id\", \"readonly\", (e => t.mutationQueue.getHighestUnacknowledgedBatchId(e)));\n }(n.localStore);\n if (-1 === e) \n // Trigger the callback right away if there is no pending writes at the moment.\n return void t.resolve();\n const r = n.ka.get(e) || [];\n r.push(t), n.ka.set(e, r);\n } catch (e) {\n const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, \"Initialization of waitForPendingWrites() operation failed\");\n t.reject(n);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */ function __PRIVATE_triggerPendingWritesCallbacks(e, t) {\n (e.ka.get(t) || []).forEach((e => {\n e.resolve();\n })), e.ka.delete(t);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */ function __PRIVATE_processUserCallback(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n let i = r.Ba[r.currentUser.toKey()];\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (i) {\n const e = i.get(t);\n e && (n ? e.reject(n) : e.resolve(), i = i.remove(t)), r.Ba[r.currentUser.toKey()] = i;\n }\n}\n\nfunction __PRIVATE_removeAndCleanupTarget(e, t, n = null) {\n e.sharedClientState.removeLocalQueryTarget(t);\n for (const r of e.Ma.get(t)) e.Fa.delete(r), n && e.Ca.$a(r, n);\n if (e.Ma.delete(t), e.isPrimaryClient) {\n e.La.gr(t).forEach((t => {\n e.La.containsKey(t) || \n // We removed the last reference for this key\n __PRIVATE_removeLimboTarget(e, t);\n }));\n }\n}\n\nfunction __PRIVATE_removeLimboTarget(e, t) {\n e.xa.delete(t.path.canonicalString());\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const n = e.Oa.get(t);\n null !== n && (__PRIVATE_remoteStoreUnlisten(e.remoteStore, n), e.Oa = e.Oa.remove(t), \n e.Na.delete(n), __PRIVATE_pumpEnqueuedLimboResolutions(e));\n}\n\nfunction __PRIVATE_updateTrackedLimbos(e, t, n) {\n for (const r of n) if (r instanceof __PRIVATE_AddedLimboDocument) e.La.addReference(r.key, t), \n __PRIVATE_trackLimboChange(e, r); else if (r instanceof __PRIVATE_RemovedLimboDocument) {\n __PRIVATE_logDebug(\"SyncEngine\", \"Document no longer in limbo: \" + r.key), e.La.removeReference(r.key, t);\n e.La.containsKey(r.key) || \n // We removed the last reference for this key\n __PRIVATE_removeLimboTarget(e, r.key);\n } else fail();\n}\n\nfunction __PRIVATE_trackLimboChange(e, t) {\n const n = t.key, r = n.path.canonicalString();\n e.Oa.get(n) || e.xa.has(r) || (__PRIVATE_logDebug(\"SyncEngine\", \"New document in limbo: \" + n), \n e.xa.add(r), __PRIVATE_pumpEnqueuedLimboResolutions(e));\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */ function __PRIVATE_pumpEnqueuedLimboResolutions(e) {\n for (;e.xa.size > 0 && e.Oa.size < e.maxConcurrentLimboResolutions; ) {\n const t = e.xa.values().next().value;\n e.xa.delete(t);\n const n = new DocumentKey(ResourcePath.fromString(t)), r = e.qa.next();\n e.Na.set(r, new LimboResolution(n)), e.Oa = e.Oa.insert(n, r), __PRIVATE_remoteStoreListen(e.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n.path)), r, \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ , __PRIVATE_ListenSequence.oe));\n }\n}\n\nasync function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = [], s = [], o = [];\n r.Fa.isEmpty() || (r.Fa.forEach(((e, _) => {\n o.push(r.Ka(_, t, n).then((e => {\n var t;\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n if ((e || n) && r.isPrimaryClient) {\n // Query state is set to `current` if:\n // - There is a view change and it is up-to-date, or,\n // - There is a global snapshot, the Target is current, and no changes to be resolved\n const i = e ? !e.fromCache : null === (t = null == n ? void 0 : n.targetChanges.get(_.targetId)) || void 0 === t ? void 0 : t.current;\n r.sharedClientState.updateQueryState(_.targetId, i ? \"current\" : \"not-current\");\n }\n // Update views if there are actual changes.\n if (e) {\n i.push(e);\n const t = __PRIVATE_LocalViewChanges.Wi(_.targetId, e);\n s.push(t);\n }\n })));\n })), await Promise.all(o), r.Ca.d_(i), await async function __PRIVATE_localStoreNotifyLocalViewChanges(e, t) {\n const n = __PRIVATE_debugCast(e);\n try {\n await n.persistence.runTransaction(\"notifyLocalViewChanges\", \"readwrite\", (e => PersistencePromise.forEach(t, (t => PersistencePromise.forEach(t.$i, (r => n.persistence.referenceDelegate.addReference(e, t.targetId, r))).next((() => PersistencePromise.forEach(t.Ui, (r => n.persistence.referenceDelegate.removeReference(e, t.targetId, r)))))))));\n } catch (e) {\n if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n __PRIVATE_logDebug(\"LocalStore\", \"Failed to update sequence numbers: \" + e);\n }\n for (const e of t) {\n const t = e.targetId;\n if (!e.fromCache) {\n const e = n.os.get(t), r = e.snapshotVersion, i = e.withLastLimboFreeSnapshotVersion(r);\n // Advance the last limbo free snapshot version\n n.os = n.os.insert(t, i);\n }\n }\n }(r.localStore, s));\n}\n\nasync function __PRIVATE_syncEngineHandleCredentialChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n if (!n.currentUser.isEqual(t)) {\n __PRIVATE_logDebug(\"SyncEngine\", \"User change. New user:\", t.toKey());\n const e = await __PRIVATE_localStoreHandleUserChange(n.localStore, t);\n n.currentUser = t, \n // Fails tasks waiting for pending writes requested by previous user.\n function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e, t) {\n e.ka.forEach((e => {\n e.forEach((e => {\n e.reject(new FirestoreError(D.CANCELLED, t));\n }));\n })), e.ka.clear();\n }(n, \"'waitForPendingWrites' promise is rejected due to a user change.\"), \n // TODO(b/114226417): Consider calling this only in the primary tab.\n n.sharedClientState.handleUserChange(t, e.removedBatchIds, e.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e.hs);\n }\n}\n\nfunction __PRIVATE_syncEngineGetRemoteKeysForTarget(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.Na.get(t);\n if (r && r.va) return __PRIVATE_documentKeySet().add(r.key);\n {\n let e = __PRIVATE_documentKeySet();\n const r = n.Ma.get(t);\n if (!r) return e;\n for (const t of r) {\n const r = n.Fa.get(t);\n e = e.unionWith(r.view.Va);\n }\n return e;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */ async function __PRIVATE_synchronizeViewAndComputeSnapshot(e, t) {\n const n = __PRIVATE_debugCast(e), r = await __PRIVATE_localStoreExecuteQuery(n.localStore, t.query, \n /* usePreviousResults= */ !0), i = t.view.ba(r);\n return n.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n, t.targetId, i.wa), \n i;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e, t) {\n const n = __PRIVATE_debugCast(e);\n return __PRIVATE_localStoreGetNewDocumentChanges(n.localStore, t).then((e => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e)));\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyBatchState(e, t, n, r) {\n const i = __PRIVATE_debugCast(e), s = await function __PRIVATE_localStoreLookupMutationDocuments(e, t) {\n const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.mutationQueue);\n return n.persistence.runTransaction(\"Lookup mutation documents\", \"readonly\", (e => r.Mn(e, t).next((t => t ? n.localDocuments.getDocuments(e, t) : PersistencePromise.resolve(null)))));\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, t);\n null !== s ? (\"pending\" === n ? \n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await __PRIVATE_fillWritePipeline(i.remoteStore) : \"acknowledged\" === n || \"rejected\" === n ? (\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n __PRIVATE_processUserCallback(i, t, r || null), __PRIVATE_triggerPendingWritesCallbacks(i, t), \n function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e, t) {\n __PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).On(t);\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, t)) : fail(), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, s)) : \n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n __PRIVATE_logDebug(\"SyncEngine\", \"Cannot apply mutation batch with id: \" + t);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyPrimaryState(e, t) {\n const n = __PRIVATE_debugCast(e);\n if (__PRIVATE_ensureWatchCallbacks(n), __PRIVATE_syncEngineEnsureWriteCallbacks(n), \n !0 === t && !0 !== n.Qa) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const e = n.sharedClientState.getAllActiveQueryTargets(), t = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e.toArray());\n n.Qa = !0, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !0);\n for (const e of t) __PRIVATE_remoteStoreListen(n.remoteStore, e);\n } else if (!1 === t && !1 !== n.Qa) {\n const e = [];\n let t = Promise.resolve();\n n.Ma.forEach(((r, i) => {\n n.sharedClientState.isLocalQueryTarget(i) ? e.push(i) : t = t.then((() => (__PRIVATE_removeAndCleanupTarget(n, i), \n __PRIVATE_localStoreReleaseTarget(n.localStore, i, \n /*keepPersistedTargetData=*/ !0)))), __PRIVATE_remoteStoreUnlisten(n.remoteStore, i);\n })), await t, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e), \n // PORTING NOTE: Multi-Tab only.\n function __PRIVATE_resetLimboDocuments(e) {\n const t = __PRIVATE_debugCast(e);\n t.Na.forEach(((e, n) => {\n __PRIVATE_remoteStoreUnlisten(t.remoteStore, n);\n })), t.La.pr(), t.Na = new Map, t.Oa = new SortedMap(DocumentKey.comparator);\n }\n /**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n // PORTING NOTE: Multi-Tab only.\n (n), n.Qa = !1, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !1);\n }\n}\n\nasync function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = [], s = [];\n for (const e of t) {\n let t;\n const n = r.Ma.get(e);\n if (n && 0 !== n.length) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n t = await __PRIVATE_localStoreAllocateTarget(r.localStore, __PRIVATE_queryToTarget(n[0]));\n for (const e of n) {\n const t = r.Fa.get(e), n = await __PRIVATE_synchronizeViewAndComputeSnapshot(r, t);\n n.snapshot && s.push(n.snapshot);\n }\n } else {\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const n = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e);\n t = await __PRIVATE_localStoreAllocateTarget(r.localStore, n), await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(n), e, \n /*current=*/ !1, t.resumeToken);\n }\n i.push(t);\n }\n return r.Ca.d_(s), i;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_synthesizeTargetToQuery(e) {\n return __PRIVATE_newQuery(e.path, e.collectionGroup, e.orderBy, e.filters, e.limit, \"F\" /* LimitType.First */ , e.startAt, e.endAt);\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_syncEngineGetActiveClients(e) {\n return function __PRIVATE_localStoreGetActiveClients(e) {\n return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).Qi();\n }(__PRIVATE_debugCast(e).localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyTargetState(e, t, n, r) {\n const i = __PRIVATE_debugCast(e);\n if (i.Qa) \n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n return void __PRIVATE_logDebug(\"SyncEngine\", \"Ignoring unexpected query state notification.\");\n const s = i.Ma.get(t);\n if (s && s.length > 0) switch (n) {\n case \"current\":\n case \"not-current\":\n {\n const e = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, __PRIVATE_queryCollectionGroup(s[0])), r = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t, \"current\" === n, ByteString.EMPTY_BYTE_STRING);\n await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, e, r);\n break;\n }\n\n case \"rejected\":\n await __PRIVATE_localStoreReleaseTarget(i.localStore, t, \n /* keepPersistedTargetData */ !0), __PRIVATE_removeAndCleanupTarget(i, t, r);\n break;\n\n default:\n fail();\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */ async function __PRIVATE_syncEngineApplyActiveTargetsChange(e, t, n) {\n const r = __PRIVATE_ensureWatchCallbacks(e);\n if (r.Qa) {\n for (const e of t) {\n if (r.Ma.has(e) && r.sharedClientState.isActiveQueryTarget(e)) {\n __PRIVATE_logDebug(\"SyncEngine\", \"Adding an already active target \" + e);\n continue;\n }\n const t = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e), n = await __PRIVATE_localStoreAllocateTarget(r.localStore, t);\n await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(t), n.targetId, \n /*current=*/ !1, n.resumeToken), __PRIVATE_remoteStoreListen(r.remoteStore, n);\n }\n for (const e of n) \n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n r.Ma.has(e) && \n // Release queries that are still active.\n await __PRIVATE_localStoreReleaseTarget(r.localStore, e, \n /* keepPersistedTargetData */ !1).then((() => {\n __PRIVATE_remoteStoreUnlisten(r.remoteStore, e), __PRIVATE_removeAndCleanupTarget(r, e);\n })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n }\n}\n\nfunction __PRIVATE_ensureWatchCallbacks(e) {\n const t = __PRIVATE_debugCast(e);\n return t.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t), \n t.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t), \n t.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t), \n t.Ca.d_ = __PRIVATE_eventManagerOnWatchChange.bind(null, t.eventManager), t.Ca.$a = __PRIVATE_eventManagerOnWatchError.bind(null, t.eventManager), \n t;\n}\n\nfunction __PRIVATE_syncEngineEnsureWriteCallbacks(e) {\n const t = __PRIVATE_debugCast(e);\n return t.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t), \n t.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t), \n t;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */ function __PRIVATE_syncEngineLoadBundle(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (\n /** Loads a bundle and returns the list of affected collection groups. */\n async function __PRIVATE_loadBundleImpl(e, t, n) {\n try {\n const r = await t.getMetadata();\n if (await function __PRIVATE_localStoreHasNewerBundle(e, t) {\n const n = __PRIVATE_debugCast(e), r = __PRIVATE_fromVersion(t.createTime);\n return n.persistence.runTransaction(\"hasNewerBundle\", \"readonly\", (e => n.Gr.getBundleMetadata(e, t.id))).then((e => !!e && e.createTime.compareTo(r) >= 0));\n }\n /**\n * Saves the given `BundleMetadata` to local persistence.\n */ (e.localStore, r)) return await t.close(), n._completeWith(function __PRIVATE_bundleSuccessProgress(e) {\n return {\n taskState: \"Success\",\n documentsLoaded: e.totalDocuments,\n bytesLoaded: e.totalBytes,\n totalDocuments: e.totalDocuments,\n totalBytes: e.totalBytes\n };\n }(r)), Promise.resolve(new Set);\n n._updateProgress(__PRIVATE_bundleInitialProgress(r));\n const i = new __PRIVATE_BundleLoader(r, e.localStore, t.serializer);\n let s = await t.Ua();\n for (;s; ) {\n const e = await i.la(s);\n e && n._updateProgress(e), s = await t.Ua();\n }\n const o = await i.complete();\n return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, o.Ia, \n /* remoteEvent */ void 0), \n // Save metadata, so loading the same bundle will skip.\n await function __PRIVATE_localStoreSaveBundle(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Save bundle\", \"readwrite\", (e => n.Gr.saveBundleMetadata(e, t)));\n }\n /**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */ (e.localStore, r), n._completeWith(o.progress), Promise.resolve(o.Pa);\n } catch (e) {\n return __PRIVATE_logWarn(\"SyncEngine\", `Loading bundle failed with ${e}`), n._failWith(e), \n Promise.resolve(new Set);\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 * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */)(r, t, n).then((e => {\n r.sharedClientState.notifyBundleLoaded(e);\n }));\n}\n\nclass __PRIVATE_MemoryOfflineComponentProvider {\n constructor() {\n this.kind = \"memory\", this.synchronizeTabs = !1;\n }\n async initialize(e) {\n this.serializer = __PRIVATE_newSerializer(e.databaseInfo.databaseId), this.sharedClientState = this.Wa(e), \n this.persistence = this.Ga(e), await this.persistence.start(), this.localStore = this.za(e), \n this.gcScheduler = this.ja(e, this.localStore), this.indexBackfillerScheduler = this.Ha(e, this.localStore);\n }\n ja(e, t) {\n return null;\n }\n Ha(e, t) {\n return null;\n }\n za(e) {\n return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer);\n }\n Ga(e) {\n return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Zr, this.serializer);\n }\n Wa(e) {\n return new __PRIVATE_MemorySharedClientState;\n }\n async terminate() {\n var e, t;\n null === (e = this.gcScheduler) || void 0 === e || e.stop(), null === (t = this.indexBackfillerScheduler) || void 0 === t || t.stop(), \n this.sharedClientState.shutdown(), await this.persistence.shutdown();\n }\n}\n\n__PRIVATE_MemoryOfflineComponentProvider.provider = {\n build: () => new __PRIVATE_MemoryOfflineComponentProvider\n};\n\nclass __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider {\n constructor(e) {\n super(), this.cacheSizeBytes = e;\n }\n ja(e, t) {\n __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate);\n const n = this.persistence.referenceDelegate.garbageCollector;\n return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);\n }\n Ga(e) {\n const t = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;\n return new __PRIVATE_MemoryPersistence((e => __PRIVATE_MemoryLruDelegate.Zr(e, t)), this.serializer);\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */ class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider {\n constructor(e, t, n) {\n super(), this.Ja = e, this.cacheSizeBytes = t, this.forceOwnership = n, this.kind = \"persistent\", \n this.synchronizeTabs = !1;\n }\n async initialize(e) {\n await super.initialize(e), await this.Ja.initialize(this, e), \n // Enqueue writes from a previous session\n await __PRIVATE_syncEngineEnsureWriteCallbacks(this.Ja.syncEngine), await __PRIVATE_fillWritePipeline(this.Ja.remoteStore), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.yi((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), \n this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), \n Promise.resolve())));\n }\n za(e) {\n return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer);\n }\n ja(e, t) {\n const n = this.persistence.referenceDelegate.garbageCollector;\n return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);\n }\n Ha(e, t) {\n const n = new __PRIVATE_IndexBackfiller(t, this.persistence);\n return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue, n);\n }\n Ga(e) {\n const t = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;\n return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t, e.clientId, n, e.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership);\n }\n Wa(e) {\n return new __PRIVATE_MemorySharedClientState;\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */ class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider {\n constructor(e, t) {\n super(e, t, /* forceOwnership= */ !1), this.Ja = e, this.cacheSizeBytes = t, this.synchronizeTabs = !0;\n }\n async initialize(e) {\n await super.initialize(e);\n const t = this.Ja.syncEngine;\n this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = {\n no: __PRIVATE_syncEngineApplyBatchState.bind(null, t),\n ro: __PRIVATE_syncEngineApplyTargetState.bind(null, t),\n io: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t),\n Qi: __PRIVATE_syncEngineGetActiveClients.bind(null, t),\n eo: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t)\n }, await this.sharedClientState.start()), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.yi((async e => {\n await __PRIVATE_syncEngineApplyPrimaryState(this.Ja.syncEngine, e), this.gcScheduler && (e && !this.gcScheduler.started ? this.gcScheduler.start() : e || this.gcScheduler.stop()), \n this.indexBackfillerScheduler && (e && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e || this.indexBackfillerScheduler.stop());\n }));\n }\n Wa(e) {\n const t = __PRIVATE_getWindow();\n if (!__PRIVATE_WebStorageSharedClientState.D(t)) throw new FirestoreError(D.UNIMPLEMENTED, \"IndexedDB persistence is only available on platforms that support LocalStorage.\");\n const n = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey);\n return new __PRIVATE_WebStorageSharedClientState(t, e.asyncQueue, n, e.clientId, e.initialUser);\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */ class OnlineComponentProvider {\n async initialize(e, t) {\n this.localStore || (this.localStore = e.localStore, this.sharedClientState = e.sharedClientState, \n this.datastore = this.createDatastore(t), this.remoteStore = this.createRemoteStore(t), \n this.eventManager = this.createEventManager(t), this.syncEngine = this.createSyncEngine(t, \n /* startAsPrimary=*/ !e.synchronizeTabs), this.sharedClientState.onlineStateHandler = e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 1 /* OnlineStateSource.SharedClientState */), \n this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), \n await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient));\n }\n createEventManager(e) {\n return function __PRIVATE_newEventManager() {\n return new __PRIVATE_EventManagerImpl;\n }();\n }\n createDatastore(e) {\n const t = __PRIVATE_newSerializer(e.databaseInfo.databaseId), n = function __PRIVATE_newConnection(e) {\n return new __PRIVATE_WebChannelConnection(e);\n }\n /** Return the Platform-specific connectivity monitor. */ (e.databaseInfo);\n return function __PRIVATE_newDatastore(e, t, n, r) {\n return new __PRIVATE_DatastoreImpl(e, t, n, r);\n }(e.authCredentials, e.appCheckCredentials, n, t);\n }\n createRemoteStore(e) {\n return function __PRIVATE_newRemoteStore(e, t, n, r, i) {\n return new __PRIVATE_RemoteStoreImpl(e, t, n, r, i);\n }\n /** Re-enables the network. Idempotent. */ (this.localStore, this.datastore, e.asyncQueue, (e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 0 /* OnlineStateSource.RemoteStore */)), function __PRIVATE_newConnectivityMonitor() {\n return __PRIVATE_BrowserConnectivityMonitor.D() ? new __PRIVATE_BrowserConnectivityMonitor : new __PRIVATE_NoopConnectivityMonitor;\n }());\n }\n createSyncEngine(e, t) {\n return function __PRIVATE_newSyncEngine(e, t, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n r, i, s, o) {\n const _ = new __PRIVATE_SyncEngineImpl(e, t, n, r, i, s);\n return o && (_.Qa = !0), _;\n }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e.initialUser, e.maxConcurrentLimboResolutions, t);\n }\n async terminate() {\n var e, t;\n await async function __PRIVATE_remoteStoreShutdown(e) {\n const t = __PRIVATE_debugCast(e);\n __PRIVATE_logDebug(\"RemoteStore\", \"RemoteStore shutting down.\"), t.L_.add(5 /* OfflineCause.Shutdown */), \n await __PRIVATE_disableNetworkInternal(t), t.k_.shutdown(), \n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n t.q_.set(\"Unknown\" /* OnlineState.Unknown */);\n }(this.remoteStore), null === (e = this.datastore) || void 0 === e || e.terminate(), \n null === (t = this.eventManager) || void 0 === t || t.terminate();\n }\n}\n\nOnlineComponentProvider.provider = {\n build: () => new OnlineComponentProvider\n};\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nfunction __PRIVATE_toByteStreamReaderHelper(e, t = 10240) {\n let n = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read() {\n if (n < e.byteLength) {\n const r = {\n value: e.slice(n, n + t),\n done: !1\n };\n return n += t, r;\n }\n return {\n done: !0\n };\n },\n async cancel() {},\n releaseLock() {},\n closed: Promise.resolve()\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/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nclass __PRIVATE_AsyncObserver {\n constructor(e) {\n this.observer = e, \n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = !1;\n }\n next(e) {\n this.muted || this.observer.next && this.Ya(this.observer.next, e);\n }\n error(e) {\n this.muted || (this.observer.error ? this.Ya(this.observer.error, e) : __PRIVATE_logError(\"Uncaught Error in snapshot listener:\", e.toString()));\n }\n Za() {\n this.muted = !0;\n }\n Ya(e, t) {\n setTimeout((() => {\n this.muted || e(t);\n }), 0);\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/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */ class __PRIVATE_BundleReaderImpl {\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n e, t) {\n this.Xa = e, this.serializer = t, \n /** Cached bundle metadata. */\n this.metadata = new __PRIVATE_Deferred, \n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n this.buffer = new Uint8Array, this.eu = function __PRIVATE_newTextDecoder() {\n return new TextDecoder(\"utf-8\");\n }(), \n // Read the metadata (which is the first element).\n this.tu().then((e => {\n e && e.ua() ? this.metadata.resolve(e.aa.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\\n ${JSON.stringify(null == e ? void 0 : e.aa)}`));\n }), (e => this.metadata.reject(e)));\n }\n close() {\n return this.Xa.cancel();\n }\n async getMetadata() {\n return this.metadata.promise;\n }\n async Ua() {\n // Makes sure metadata is read before proceeding.\n return await this.getMetadata(), this.tu();\n }\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */ async tu() {\n const e = await this.nu();\n if (null === e) return null;\n const t = this.eu.decode(e), n = Number(t);\n isNaN(n) && this.ru(`length string (${t}) is not valid number`);\n const r = await this.iu(n);\n return new __PRIVATE_SizedBundleElement(JSON.parse(r), e.length + n);\n }\n /** First index of '{' from the underlying buffer. */ su() {\n return this.buffer.findIndex((e => e === \"{\".charCodeAt(0)));\n }\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */ async nu() {\n for (;this.su() < 0; ) {\n if (await this.ou()) break;\n }\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (0 === this.buffer.length) return null;\n const e = this.su();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n e < 0 && this.ru(\"Reached the end of bundle when a length string is expected.\");\n const t = this.buffer.slice(0, e);\n // Update the internal buffer to drop the read length.\n return this.buffer = this.buffer.slice(e), t;\n }\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */ async iu(e) {\n for (;this.buffer.length < e; ) {\n await this.ou() && this.ru(\"Reached the end of bundle when more is expected.\");\n }\n const t = this.eu.decode(this.buffer.slice(0, e));\n // Update the internal buffer to drop the read json string.\n return this.buffer = this.buffer.slice(e), t;\n }\n ru(e) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n throw this.Xa.cancel(), new Error(`Invalid bundle format: ${e}`);\n }\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */ async ou() {\n const e = await this.Xa.read();\n if (!e.done) {\n const t = new Uint8Array(this.buffer.length + e.value.length);\n t.set(this.buffer), t.set(e.value, this.buffer.length), this.buffer = t;\n }\n return e.done;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nclass Transaction$2 {\n constructor(e) {\n this.datastore = e, \n // The version of each document that was read during this transaction.\n this.readVersions = new Map, this.mutations = [], this.committed = !1, \n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n this.lastTransactionError = null, \n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n this.writtenDocs = new Set;\n }\n async lookup(e) {\n if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(D.INVALID_ARGUMENT, \"Firestore transactions require all reads to be executed before all writes.\"), \n this.lastTransactionError;\n const t = await async function __PRIVATE_invokeBatchGetDocumentsRpc(e, t) {\n const n = __PRIVATE_debugCast(e), r = {\n documents: t.map((e => __PRIVATE_toName(n.serializer, e)))\n }, i = await n.Lo(\"BatchGetDocuments\", n.serializer.databaseId, ResourcePath.emptyPath(), r, t.length), s = new Map;\n i.forEach((e => {\n const t = __PRIVATE_fromBatchGetDocumentsResponse(n.serializer, e);\n s.set(t.key.toString(), t);\n }));\n const o = [];\n return t.forEach((e => {\n const t = s.get(e.toString());\n __PRIVATE_hardAssert(!!t), o.push(t);\n })), o;\n }(this.datastore, e);\n return t.forEach((e => this.recordVersion(e))), t;\n }\n set(e, t) {\n this.write(t.toMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());\n }\n update(e, t) {\n try {\n this.write(t.toMutation(e, this.preconditionForUpdate(e)));\n } catch (e) {\n this.lastTransactionError = e;\n }\n this.writtenDocs.add(e.toString());\n }\n delete(e) {\n this.write(new __PRIVATE_DeleteMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());\n }\n async commit() {\n if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError;\n const e = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach((t => {\n e.delete(t.key.toString());\n })), \n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n e.forEach(((e, t) => {\n const n = DocumentKey.fromPath(t);\n this.mutations.push(new __PRIVATE_VerifyMutation(n, this.precondition(n)));\n })), await async function __PRIVATE_invokeCommitRpc(e, t) {\n const n = __PRIVATE_debugCast(e), r = {\n writes: t.map((e => toMutation(n.serializer, e)))\n };\n await n.Mo(\"Commit\", n.serializer.databaseId, ResourcePath.emptyPath(), r);\n }(this.datastore, this.mutations), this.committed = !0;\n }\n recordVersion(e) {\n let t;\n if (e.isFoundDocument()) t = e.version; else {\n if (!e.isNoDocument()) throw fail();\n // Represent a deleted doc using SnapshotVersion.min().\n t = SnapshotVersion.min();\n }\n const n = this.readVersions.get(e.key.toString());\n if (n) {\n if (!t.isEqual(n)) \n // This transaction will fail no matter what.\n throw new FirestoreError(D.ABORTED, \"Document version changed between two reads.\");\n } else this.readVersions.set(e.key.toString(), t);\n }\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */ precondition(e) {\n const t = this.readVersions.get(e.toString());\n return !this.writtenDocs.has(e.toString()) && t ? t.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(t) : Precondition.none();\n }\n /**\n * Returns the precondition for a document if the operation is an update.\n */ preconditionForUpdate(e) {\n const t = this.readVersions.get(e.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(e.toString()) && t) {\n if (t.isEqual(SnapshotVersion.min())) \n // The document doesn't exist, so fail the transaction.\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(D.INVALID_ARGUMENT, \"Can't update a document that doesn't exist.\");\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(t);\n }\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(!0);\n }\n write(e) {\n this.ensureCommitNotCalled(), this.mutations.push(e);\n }\n ensureCommitNotCalled() {}\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */ class __PRIVATE_TransactionRunner {\n constructor(e, t, n, r, i) {\n this.asyncQueue = e, this.datastore = t, this.options = n, this.updateFunction = r, \n this.deferred = i, this._u = n.maxAttempts, this.t_ = new __PRIVATE_ExponentialBackoff(this.asyncQueue, \"transaction_retry\" /* TimerId.TransactionRetry */);\n }\n /** Runs the transaction and sets the result on deferred. */ au() {\n this._u -= 1, this.uu();\n }\n uu() {\n this.t_.Go((async () => {\n const e = new Transaction$2(this.datastore), t = this.cu(e);\n t && t.then((t => {\n this.asyncQueue.enqueueAndForget((() => e.commit().then((() => {\n this.deferred.resolve(t);\n })).catch((e => {\n this.lu(e);\n }))));\n })).catch((e => {\n this.lu(e);\n }));\n }));\n }\n cu(e) {\n try {\n const t = this.updateFunction(e);\n return !__PRIVATE_isNullOrUndefined(t) && t.catch && t.then ? t : (this.deferred.reject(Error(\"Transaction callback must return a Promise\")), \n null);\n } catch (e) {\n // Do not retry errors thrown by user provided updateFunction.\n return this.deferred.reject(e), null;\n }\n }\n lu(e) {\n this._u > 0 && this.hu(e) ? (this._u -= 1, this.asyncQueue.enqueueAndForget((() => (this.uu(), \n Promise.resolve())))) : this.deferred.reject(e);\n }\n hu(e) {\n if (\"FirebaseError\" === e.name) {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const t = e.code;\n return \"aborted\" === t || \"failed-precondition\" === t || \"already-exists\" === t || !__PRIVATE_isPermanentError(t);\n }\n return !1;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the //\n * pieces of the client SDK architecture. It is responsible for creating the //\n * async queue that is shared by all of the other components in the system. //\n */\nclass FirestoreClient {\n constructor(e, t, \n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n n, r, i) {\n this.authCredentials = e, this.appCheckCredentials = t, this.asyncQueue = n, this.databaseInfo = r, \n this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.newId(), this.authCredentialListener = () => Promise.resolve(), \n this.appCheckCredentialListener = () => Promise.resolve(), this._uninitializedComponentsProvider = i, \n this.authCredentials.start(n, (async e => {\n __PRIVATE_logDebug(\"FirestoreClient\", \"Received user=\", e.uid), await this.authCredentialListener(e), \n this.user = e;\n })), this.appCheckCredentials.start(n, (e => (__PRIVATE_logDebug(\"FirestoreClient\", \"Received new app check token=\", e), \n this.appCheckCredentialListener(e, this.user))));\n }\n get configuration() {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: 100\n };\n }\n setCredentialChangeListener(e) {\n this.authCredentialListener = e;\n }\n setAppCheckTokenChangeListener(e) {\n this.appCheckCredentialListener = e;\n }\n terminate() {\n this.asyncQueue.enterRestrictedMode();\n const e = new __PRIVATE_Deferred;\n return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), \n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e.resolve();\n } catch (t) {\n const n = __PRIVATE_wrapInUserErrorIfRecoverable(t, \"Failed to shutdown persistence\");\n e.reject(n);\n }\n })), e.promise;\n }\n}\n\nasync function __PRIVATE_setOfflineComponentProvider(e, t) {\n e.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(\"FirestoreClient\", \"Initializing OfflineComponentProvider\");\n const n = e.configuration;\n await t.initialize(n);\n let r = n.initialUser;\n e.setCredentialChangeListener((async e => {\n r.isEqual(e) || (await __PRIVATE_localStoreHandleUserChange(t.localStore, e), r = e);\n })), \n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n t.persistence.setDatabaseDeletedListener((() => e.terminate())), e._offlineComponents = t;\n}\n\nasync function __PRIVATE_setOnlineComponentProvider(e, t) {\n e.asyncQueue.verifyOperationInProgress();\n const n = await __PRIVATE_ensureOfflineComponents(e);\n __PRIVATE_logDebug(\"FirestoreClient\", \"Initializing OnlineComponentProvider\"), await t.initialize(n, e.configuration), \n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n e.setCredentialChangeListener((e => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, e))), \n e.setAppCheckTokenChangeListener(((e, n) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, n))), \n e._onlineComponents = t;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */ async function __PRIVATE_ensureOfflineComponents(e) {\n if (!e._offlineComponents) if (e._uninitializedComponentsProvider) {\n __PRIVATE_logDebug(\"FirestoreClient\", \"Using user provided OfflineComponentProvider\");\n try {\n await __PRIVATE_setOfflineComponentProvider(e, e._uninitializedComponentsProvider._offline);\n } catch (t) {\n const n = t;\n if (!function __PRIVATE_canFallbackFromIndexedDbError(e) {\n return \"FirebaseError\" === e.name ? e.code === D.FAILED_PRECONDITION || e.code === D.UNIMPLEMENTED : !(\"undefined\" != typeof DOMException && e instanceof DOMException) || \n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n 22 === e.code || 20 === e.code || \n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n 11 === e.code;\n }(n)) throw n;\n __PRIVATE_logWarn(\"Error using user provided cache. Falling back to memory cache: \" + n), \n await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_MemoryOfflineComponentProvider);\n }\n } else __PRIVATE_logDebug(\"FirestoreClient\", \"Using default OfflineComponentProvider\"), \n await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_MemoryOfflineComponentProvider);\n return e._offlineComponents;\n}\n\nasync function __PRIVATE_ensureOnlineComponents(e) {\n return e._onlineComponents || (e._uninitializedComponentsProvider ? (__PRIVATE_logDebug(\"FirestoreClient\", \"Using user provided OnlineComponentProvider\"), \n await __PRIVATE_setOnlineComponentProvider(e, e._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(\"FirestoreClient\", \"Using default OnlineComponentProvider\"), \n await __PRIVATE_setOnlineComponentProvider(e, new OnlineComponentProvider))), e._onlineComponents;\n}\n\nfunction __PRIVATE_getPersistence(e) {\n return __PRIVATE_ensureOfflineComponents(e).then((e => e.persistence));\n}\n\nfunction __PRIVATE_getLocalStore(e) {\n return __PRIVATE_ensureOfflineComponents(e).then((e => e.localStore));\n}\n\nfunction __PRIVATE_getRemoteStore(e) {\n return __PRIVATE_ensureOnlineComponents(e).then((e => e.remoteStore));\n}\n\nfunction __PRIVATE_getSyncEngine(e) {\n return __PRIVATE_ensureOnlineComponents(e).then((e => e.syncEngine));\n}\n\nfunction __PRIVATE_getDatastore(e) {\n return __PRIVATE_ensureOnlineComponents(e).then((e => e.datastore));\n}\n\nasync function __PRIVATE_getEventManager(e) {\n const t = await __PRIVATE_ensureOnlineComponents(e), n = t.eventManager;\n return n.onListen = __PRIVATE_syncEngineListen.bind(null, t.syncEngine), n.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t.syncEngine), \n n.onFirstRemoteStoreListen = __PRIVATE_triggerRemoteStoreListen.bind(null, t.syncEngine), \n n.onLastRemoteStoreUnlisten = __PRIVATE_triggerRemoteStoreUnlisten.bind(null, t.syncEngine), \n n;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */ function __PRIVATE_firestoreClientEnableNetwork(e) {\n return e.asyncQueue.enqueue((async () => {\n const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);\n return t.setNetworkEnabled(!0), function __PRIVATE_remoteStoreEnableNetwork(e) {\n const t = __PRIVATE_debugCast(e);\n return t.L_.delete(0 /* OfflineCause.UserDisabled */), __PRIVATE_enableNetworkInternal(t);\n }(n);\n }));\n}\n\n/** Disables the network connection. Pending operations will not complete. */ function __PRIVATE_firestoreClientDisableNetwork(e) {\n return e.asyncQueue.enqueue((async () => {\n const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);\n return t.setNetworkEnabled(!1), async function __PRIVATE_remoteStoreDisableNetwork(e) {\n const t = __PRIVATE_debugCast(e);\n t.L_.add(0 /* OfflineCause.UserDisabled */), await __PRIVATE_disableNetworkInternal(t), \n // Set the OnlineState to Offline so get()s return from cache, etc.\n t.q_.set(\"Offline\" /* OnlineState.Offline */);\n }(n);\n }));\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */ function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e, t) {\n const n = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_readDocumentFromCache(e, t, n) {\n try {\n const r = await function __PRIVATE_localStoreReadDocument(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"read document\", \"readonly\", (e => n.localDocuments.getDocument(e, t)));\n }(e, t);\n r.isFoundDocument() ? n.resolve(r) : r.isNoDocument() ? n.resolve(null) : n.reject(new FirestoreError(D.UNAVAILABLE, \"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)\"));\n } catch (e) {\n const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to get document '${t} from cache`);\n n.reject(r);\n }\n }\n /**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e, t, n = {}) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_readDocumentViaSnapshotListener(e, t, n, r, i) {\n const s = new __PRIVATE_AsyncObserver({\n next: _ => {\n // Mute and remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n s.Za(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o)));\n const a = _.docs.has(n);\n !a && _.fromCache ? \n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n i.reject(new FirestoreError(D.UNAVAILABLE, \"Failed to get document because the client is offline.\")) : a && _.fromCache && r && \"server\" === r.source ? i.reject(new FirestoreError(D.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to \"server\" to retrieve the cached document.)')) : i.resolve(_);\n },\n error: e => i.reject(e)\n }), o = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n.path), s, {\n includeMetadataChanges: !0,\n _a: !0\n });\n return __PRIVATE_eventManagerListen(e, o);\n }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e, t) {\n const n = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_executeQueryFromCache(e, t, n) {\n try {\n const r = await __PRIVATE_localStoreExecuteQuery(e, t, \n /* usePreviousResults= */ !0), i = new __PRIVATE_View(t, r.Ts), s = i.ma(r.documents), o = i.applyChanges(s, \n /* limboResolutionEnabled= */ !1);\n n.resolve(o.snapshot);\n } catch (e) {\n const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to execute query '${t} against cache`);\n n.reject(r);\n }\n }\n /**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e, t, n = {}) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_executeQueryViaSnapshotListener(e, t, n, r, i) {\n const s = new __PRIVATE_AsyncObserver({\n next: n => {\n // Mute and remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n s.Za(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))), n.fromCache && \"server\" === r.source ? i.reject(new FirestoreError(D.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to \"server\" to retrieve the cached documents.)')) : i.resolve(n);\n },\n error: e => i.reject(e)\n }), o = new __PRIVATE_QueryListener(n, s, {\n includeMetadataChanges: !0,\n _a: !0\n });\n return __PRIVATE_eventManagerListen(e, o);\n }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise;\n}\n\nfunction __PRIVATE_firestoreClientRunAggregateQuery(e, t, n) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => {\n // Implement and call executeAggregateQueryViaSnapshotListener, similar\n // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n // above\n try {\n // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n const i = await __PRIVATE_getDatastore(e);\n r.resolve(async function __PRIVATE_invokeRunAggregationQueryRpc(e, t, n) {\n var r;\n const i = __PRIVATE_debugCast(e), {request: s, ut: o, parent: _} = __PRIVATE_toRunAggregationQueryRequest(i.serializer, __PRIVATE_queryToAggregateTarget(t), n);\n i.connection.Fo || delete s.parent;\n const a = (await i.Lo(\"RunAggregationQuery\", i.serializer.databaseId, _, s, \n /*expectedResponseCount=*/ 1)).filter((e => !!e.result));\n // Omit RunAggregationQueryResponse that only contain readTimes.\n __PRIVATE_hardAssert(1 === a.length);\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const u = null === (r = a[0].result) || void 0 === r ? void 0 : r.aggregateFields;\n return Object.keys(u).reduce(((e, t) => (e[o[t]] = u[t], e)), {});\n }(i, t, n));\n } catch (e) {\n r.reject(e);\n }\n })), r.promise;\n}\n\nfunction __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e, t) {\n const n = new __PRIVATE_AsyncObserver(t);\n return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_addSnapshotsInSyncListener(e, t) {\n __PRIVATE_debugCast(e).Y_.add(t), \n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n t.next();\n }(await __PRIVATE_getEventManager(e), n))), () => {\n n.Za(), e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_removeSnapshotsInSyncListener(e, t) {\n __PRIVATE_debugCast(e).Y_.delete(t);\n }(await __PRIVATE_getEventManager(e), n)));\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */ function __PRIVATE_firestoreClientLoadBundle(e, t, n, r) {\n const i = function __PRIVATE_createBundleReader(e, t) {\n let n;\n n = \"string\" == typeof e ? __PRIVATE_newTextEncoder().encode(e) : e;\n return function __PRIVATE_newBundleReader(e, t) {\n return new __PRIVATE_BundleReaderImpl(e, t);\n }(function __PRIVATE_toByteStreamReader(e, t) {\n if (e instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e, t);\n if (e instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e), t);\n if (e instanceof ReadableStream) return e.getReader();\n throw new Error(\"Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream\");\n }(n), t);\n }(n, __PRIVATE_newSerializer(t));\n e.asyncQueue.enqueueAndForget((async () => {\n __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e), i, r);\n }));\n}\n\nfunction __PRIVATE_firestoreClientGetNamedQuery(e, t) {\n return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreGetNamedQuery(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Get named query\", \"readonly\", (e => n.Gr.getNamedQuery(e, t)));\n }(await __PRIVATE_getLocalStore(e), t)));\n}\n\nfunction __PRIVATE_firestoreClientSetIndexConfiguration(e, t) {\n return e.asyncQueue.enqueue((async () => async function __PRIVATE_localStoreConfigureFieldIndexes(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.indexManager, i = [];\n return n.persistence.runTransaction(\"Configure indexes\", \"readwrite\", (e => r.getFieldIndexes(e).next((n => \n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n function __PRIVATE_diffArrays(e, t, n, r, i) {\n e = [ ...e ], t = [ ...t ], e.sort(n), t.sort(n);\n const s = e.length, o = t.length;\n let _ = 0, a = 0;\n for (;_ < o && a < s; ) {\n const s = n(e[a], t[_]);\n s < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n i(e[a++]) : s > 0 ? \n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n r(t[_++]) : (_++, a++);\n }\n for (;_ < o; ) r(t[_++]);\n for (;a < s; ) i(e[a++]);\n }\n /**\n * Verifies equality for an array of primitives.\n *\n * @private\n * @internal\n * @param left Array of primitives.\n * @param right Array of primitives.\n * @return True if arrays are equal.\n */ (n, t, __PRIVATE_fieldIndexSemanticComparator, (t => {\n i.push(r.addFieldIndex(e, t));\n }), (t => {\n i.push(r.deleteFieldIndex(e, t));\n })))).next((() => PersistencePromise.waitFor(i)))));\n }(await __PRIVATE_getLocalStore(e), t)));\n}\n\nfunction __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e, t) {\n return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e, t) {\n __PRIVATE_debugCast(e).ss.zi = t;\n }(await __PRIVATE_getLocalStore(e), t)));\n}\n\nfunction __PRIVATE_firestoreClientDeleteAllFieldIndexes(e) {\n return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreDeleteAllFieldIndexes(e) {\n const t = __PRIVATE_debugCast(e), n = t.indexManager;\n return t.persistence.runTransaction(\"Delete All Indexes\", \"readwrite\", (e => n.deleteAllFieldIndexes(e)));\n }\n /**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // The format of the LocalStorage key that stores the client state is:\n // firestore_clients__\n (await __PRIVATE_getLocalStore(e))));\n}\n\n/**\n * @license\n * Copyright 2023 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 * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nfunction __PRIVATE_cloneLongPollingOptions(e) {\n const t = {};\n return void 0 !== e.timeoutSeconds && (t.timeoutSeconds = e.timeoutSeconds), t;\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 */ const we = new Map;\n\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction __PRIVATE_validateNonEmptyArgument(e, t, n) {\n if (!n) throw new FirestoreError(D.INVALID_ARGUMENT, `Function ${e}() cannot be called with an empty ${t}.`);\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */ function __PRIVATE_validateIsNotUsedTogether(e, t, n, r) {\n if (!0 === t && !0 === r) throw new FirestoreError(D.INVALID_ARGUMENT, `${e} and ${n} cannot be used together.`);\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */ function __PRIVATE_validateDocumentPath(e) {\n if (!DocumentKey.isDocumentKey(e)) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`);\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */ function __PRIVATE_validateCollectionPath(e) {\n if (DocumentKey.isDocumentKey(e)) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`);\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\n/** Returns a string describing the type / value of the provided input. */\nfunction __PRIVATE_valueDescription(e) {\n if (void 0 === e) return \"undefined\";\n if (null === e) return \"null\";\n if (\"string\" == typeof e) return e.length > 20 && (e = `${e.substring(0, 20)}...`), \n JSON.stringify(e);\n if (\"number\" == typeof e || \"boolean\" == typeof e) return \"\" + e;\n if (\"object\" == typeof e) {\n if (e instanceof Array) return \"an array\";\n {\n const t = \n /** try to get the constructor name for an object. */\n function __PRIVATE_tryGetCustomObjectType(e) {\n if (e.constructor) return e.constructor.name;\n return null;\n }\n /**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */ (e);\n return t ? `a custom ${t} object` : \"an object\";\n }\n }\n return \"function\" == typeof e ? \"a function\" : fail();\n}\n\nfunction __PRIVATE_cast(e, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nt) {\n if (\"_delegate\" in e && (\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n e = e._delegate), !(e instanceof t)) {\n if (t.name === e.constructor.name) throw new FirestoreError(D.INVALID_ARGUMENT, \"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?\");\n {\n const n = __PRIVATE_valueDescription(e);\n throw new FirestoreError(D.INVALID_ARGUMENT, `Expected type '${t.name}', but it was: ${n}`);\n }\n }\n return e;\n}\n\nfunction __PRIVATE_validatePositiveNumber(e, t) {\n if (t <= 0) throw new FirestoreError(D.INVALID_ARGUMENT, `Function ${e}() requires a positive number, but it was: ${t}.`);\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// settings() defaults:\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass FirestoreSettingsImpl {\n constructor(e) {\n var t, n;\n if (void 0 === e.host) {\n if (void 0 !== e.ssl) throw new FirestoreError(D.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n this.host = \"firestore.googleapis.com\", this.ssl = true;\n } else this.host = e.host, this.ssl = null === (t = e.ssl) || void 0 === t || t;\n if (this.credentials = e.credentials, this.ignoreUndefinedProperties = !!e.ignoreUndefinedProperties, \n this.localCache = e.localCache, void 0 === e.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {\n if (-1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new FirestoreError(D.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n this.cacheSizeBytes = e.cacheSizeBytes;\n }\n __PRIVATE_validateIsNotUsedTogether(\"experimentalForceLongPolling\", e.experimentalForceLongPolling, \"experimentalAutoDetectLongPolling\", e.experimentalAutoDetectLongPolling), \n this.experimentalForceLongPolling = !!e.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === e.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : \n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling = !!e.experimentalAutoDetectLongPolling, \n this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(null !== (n = e.experimentalLongPollingOptions) && void 0 !== n ? n : {}), \n function __PRIVATE_validateLongPollingOptions(e) {\n if (void 0 !== e.timeoutSeconds) {\n if (isNaN(e.timeoutSeconds)) throw new FirestoreError(D.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);\n if (e.timeoutSeconds < 5) throw new FirestoreError(D.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);\n if (e.timeoutSeconds > 30) throw new FirestoreError(D.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`);\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 * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!e.useFetchStreams;\n }\n isEqual(e) {\n return this.host === e.host && this.ssl === e.ssl && this.credentials === e.credentials && this.cacheSizeBytes === e.cacheSizeBytes && this.experimentalForceLongPolling === e.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(e, t) {\n return e.timeoutSeconds === t.timeoutSeconds;\n }(this.experimentalLongPollingOptions, e.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e.ignoreUndefinedProperties && this.useFetchStreams === e.useFetchStreams;\n }\n}\n\nclass Firestore$1 {\n /** @hideconstructor */\n constructor(e, t, n, r) {\n this._authCredentials = e, this._appCheckCredentials = t, this._databaseId = n, \n this._app = r, \n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n this.type = \"firestore-lite\", this._persistenceKey = \"(lite)\", this._settings = new FirestoreSettingsImpl({}), \n this._settingsFrozen = !1, \n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down. Otherwise, Firestore is not terminated,\n // which can mean either the FirestoreClient is in the process of starting,\n // or restarting.\n this._terminateTask = \"notTerminated\";\n }\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */ get app() {\n if (!this._app) throw new FirestoreError(D.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is not available\");\n return this._app;\n }\n get _initialized() {\n return this._settingsFrozen;\n }\n get _terminated() {\n return \"notTerminated\" !== this._terminateTask;\n }\n _setSettings(e) {\n if (this._settingsFrozen) throw new FirestoreError(D.FAILED_PRECONDITION, \"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.\");\n this._settings = new FirestoreSettingsImpl(e), void 0 !== e.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(e) {\n if (!e) return new __PRIVATE_EmptyAuthCredentialsProvider;\n switch (e.type) {\n case \"firstParty\":\n return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex || \"0\", e.iamToken || null, e.authTokenFactory || null);\n\n case \"provider\":\n return e.client;\n\n default:\n throw new FirestoreError(D.INVALID_ARGUMENT, \"makeAuthCredentialsProvider failed due to invalid credential type\");\n }\n }(e.credentials));\n }\n _getSettings() {\n return this._settings;\n }\n _freezeSettings() {\n return this._settingsFrozen = !0, this._settings;\n }\n _delete() {\n // The `_terminateTask` must be assigned future that completes when\n // terminate is complete. The existence of this future puts SDK in state\n // that will not accept further API interaction.\n return \"notTerminated\" === this._terminateTask && (this._terminateTask = this._terminate()), \n this._terminateTask;\n }\n async _restart() {\n // The `_terminateTask` must equal 'notTerminated' after restart to\n // signal that client is in a state that accepts API calls.\n \"notTerminated\" === this._terminateTask ? await this._terminate() : this._terminateTask = \"notTerminated\";\n }\n /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */ _terminate() {\n /**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\n return function __PRIVATE_removeComponents(e) {\n const t = we.get(e);\n t && (__PRIVATE_logDebug(\"ComponentProvider\", \"Removing Datastore\"), we.delete(e), \n t.terminate());\n }(this), Promise.resolve();\n }\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */ function connectFirestoreEmulator(e, t, n, r = {}) {\n var i;\n const s = (e = __PRIVATE_cast(e, Firestore$1))._getSettings(), o = `${t}:${n}`;\n if (\"firestore.googleapis.com\" !== s.host && s.host !== o && __PRIVATE_logWarn(\"Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.\"), \n e._setSettings(Object.assign(Object.assign({}, s), {\n host: o,\n ssl: !1\n })), r.mockUserToken) {\n let t, n;\n if (\"string\" == typeof r.mockUserToken) t = r.mockUserToken, n = User.MOCK_USER; else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n t = createMockUserToken(r.mockUserToken, null === (i = e._app) || void 0 === i ? void 0 : i.options.projectId);\n const s = r.mockUserToken.sub || r.mockUserToken.user_id;\n if (!s) throw new FirestoreError(D.INVALID_ARGUMENT, \"mockUserToken must contain 'sub' or 'user_id' field!\");\n n = new User(s);\n }\n e._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t, n));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */ class Query {\n // This is the lite version of the Query class in the main SDK.\n /** @hideconstructor protected */\n constructor(e, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n t, n) {\n this.converter = t, this._query = n, \n /** The type of this Firestore reference. */\n this.type = \"query\", this.firestore = e;\n }\n withConverter(e) {\n return new Query(this.firestore, e, this._query);\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */ class DocumentReference {\n /** @hideconstructor */\n constructor(e, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n t, n) {\n this.converter = t, this._key = n, \n /** The type of this Firestore reference. */\n this.type = \"document\", this.firestore = e;\n }\n get _path() {\n return this._key.path;\n }\n /**\n * The document's identifier within its collection.\n */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */ get path() {\n return this._key.path.canonicalString();\n }\n /**\n * The collection this `DocumentReference` belongs to.\n */ get parent() {\n return new CollectionReference(this.firestore, this.converter, this._key.path.popLast());\n }\n withConverter(e) {\n return new DocumentReference(this.firestore, e, this._key);\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */ class CollectionReference extends Query {\n /** @hideconstructor */\n constructor(e, t, n) {\n super(e, t, __PRIVATE_newQueryForPath(n)), this._path = n, \n /** The type of this Firestore reference. */\n this.type = \"collection\";\n }\n /** The collection's identifier. */ get id() {\n return this._query.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */ get path() {\n return this._query.path.canonicalString();\n }\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */ get parent() {\n const e = this._path.popLast();\n return e.isEmpty() ? null : new DocumentReference(this.firestore, \n /* converter= */ null, new DocumentKey(e));\n }\n withConverter(e) {\n return new CollectionReference(this.firestore, e, this._path);\n }\n}\n\nfunction collection(e, t, ...n) {\n if (e = getModularInstance(e), __PRIVATE_validateNonEmptyArgument(\"collection\", \"path\", t), e instanceof Firestore$1) {\n const r = ResourcePath.fromString(t, ...n);\n return __PRIVATE_validateCollectionPath(r), new CollectionReference(e, /* converter= */ null, r);\n }\n {\n if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(D.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const r = e._path.child(ResourcePath.fromString(t, ...n));\n return __PRIVATE_validateCollectionPath(r), new CollectionReference(e.firestore, \n /* converter= */ null, r);\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */ function collectionGroup(e, t) {\n if (e = __PRIVATE_cast(e, Firestore$1), __PRIVATE_validateNonEmptyArgument(\"collectionGroup\", \"collection id\", t), \n t.indexOf(\"/\") >= 0) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);\n return new Query(e, \n /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(e) {\n return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e);\n }(t));\n}\n\nfunction doc(e, t, ...n) {\n if (e = getModularInstance(e), \n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n 1 === arguments.length && (t = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument(\"doc\", \"path\", t), \n e instanceof Firestore$1) {\n const r = ResourcePath.fromString(t, ...n);\n return __PRIVATE_validateDocumentPath(r), new DocumentReference(e, \n /* converter= */ null, new DocumentKey(r));\n }\n {\n if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(D.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const r = e._path.child(ResourcePath.fromString(t, ...n));\n return __PRIVATE_validateDocumentPath(r), new DocumentReference(e.firestore, e instanceof CollectionReference ? e.converter : null, new DocumentKey(r));\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function refEqual(e, t) {\n return e = getModularInstance(e), t = getModularInstance(t), (e instanceof DocumentReference || e instanceof CollectionReference) && (t instanceof DocumentReference || t instanceof CollectionReference) && (e.firestore === t.firestore && e.path === t.path && e.converter === t.converter);\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function queryEqual(e, t) {\n return e = getModularInstance(e), t = getModularInstance(t), e instanceof Query && t instanceof Query && (e.firestore === t.firestore && __PRIVATE_queryEquals(e._query, t._query) && e.converter === t.converter);\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 */ class __PRIVATE_AsyncQueueImpl {\n constructor(e = Promise.resolve()) {\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n this.Pu = [], \n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n this.Iu = !1, \n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n this.Tu = [], \n // visible for testing\n this.Eu = null, \n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.du = !1, \n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n this.Au = !1, \n // List of TimerIds to fast-forward delays for.\n this.Ru = [], \n // Backoff timer used to schedule retries for retryable operations\n this.t_ = new __PRIVATE_ExponentialBackoff(this, \"async_queue_retry\" /* TimerId.AsyncQueueRetry */), \n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n this.Vu = () => {\n const e = getDocument();\n e && __PRIVATE_logDebug(\"AsyncQueue\", \"Visibility state changed to \" + e.visibilityState), \n this.t_.jo();\n }, this.mu = e;\n const t = getDocument();\n t && \"function\" == typeof t.addEventListener && t.addEventListener(\"visibilitychange\", this.Vu);\n }\n get isShuttingDown() {\n return this.Iu;\n }\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */ enqueueAndForget(e) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(e);\n }\n enqueueAndForgetEvenWhileRestricted(e) {\n this.fu(), \n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.gu(e);\n }\n enterRestrictedMode(e) {\n if (!this.Iu) {\n this.Iu = !0, this.Au = e || !1;\n const t = getDocument();\n t && \"function\" == typeof t.removeEventListener && t.removeEventListener(\"visibilitychange\", this.Vu);\n }\n }\n enqueue(e) {\n if (this.fu(), this.Iu) \n // Return a Promise which never resolves.\n return new Promise((() => {}));\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const t = new __PRIVATE_Deferred;\n return this.gu((() => this.Iu && this.Au ? Promise.resolve() : (e().then(t.resolve, t.reject), \n t.promise))).then((() => t.promise));\n }\n enqueueRetryable(e) {\n this.enqueueAndForget((() => (this.Pu.push(e), this.pu())));\n }\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */ async pu() {\n if (0 !== this.Pu.length) {\n try {\n await this.Pu[0](), this.Pu.shift(), this.t_.reset();\n } catch (e) {\n if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n // Failure will be handled by AsyncQueue\n __PRIVATE_logDebug(\"AsyncQueue\", \"Operation failed with retryable error: \" + e);\n }\n this.Pu.length > 0 && \n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.t_.Go((() => this.pu()));\n }\n }\n gu(e) {\n const t = this.mu.then((() => (this.du = !0, e().catch((e => {\n this.Eu = e, this.du = !1;\n const t = \n /**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\n function __PRIVATE_getMessageOrStack(e) {\n let t = e.message || \"\";\n e.stack && (t = e.stack.includes(e.message) ? e.stack : e.message + \"\\n\" + e.stack);\n return t;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (e);\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw __PRIVATE_logError(\"INTERNAL UNHANDLED ERROR: \", t), e;\n })).then((e => (this.du = !1, e))))));\n return this.mu = t, t;\n }\n enqueueAfterDelay(e, t, n) {\n this.fu(), \n // Fast-forward delays for timerIds that have been overridden.\n this.Ru.indexOf(e) > -1 && (t = 0);\n const r = DelayedOperation.createAndSchedule(this, e, t, n, (e => this.yu(e)));\n return this.Tu.push(r), r;\n }\n fu() {\n this.Eu && fail();\n }\n verifyOperationInProgress() {}\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */ async wu() {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let e;\n do {\n e = this.mu, await e;\n } while (e !== this.mu);\n }\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */ Su(e) {\n for (const t of this.Tu) if (t.timerId === e) return !0;\n return !1;\n }\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */ bu(e) {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.wu().then((() => {\n // Run ops in the same order they'd run if they ran naturally.\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.Tu.sort(((e, t) => e.targetTimeMs - t.targetTimeMs));\n for (const t of this.Tu) if (t.skipDelay(), \"all\" /* TimerId.All */ !== e && t.timerId === e) break;\n return this.wu();\n }));\n }\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */ Du(e) {\n this.Ru.push(e);\n }\n /** Called once a DelayedOperation is run or canceled. */ yu(e) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const t = this.Tu.indexOf(e);\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.Tu.splice(t, 1);\n }\n}\n\nfunction __PRIVATE_isPartialObserver(e) {\n /**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\n return function __PRIVATE_implementsAnyMethods(e, t) {\n if (\"object\" != typeof e || null === e) return !1;\n const n = e;\n for (const e of t) if (e in n && \"function\" == typeof n[e]) return !0;\n return !1;\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 * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */ (e, [ \"next\", \"error\", \"complete\" ]);\n}\n\nclass LoadBundleTask {\n constructor() {\n this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred, \n this._lastProgress = {\n taskState: \"Running\",\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n }\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */ onProgress(e, t, n) {\n this._progressObserver = {\n next: e,\n error: t,\n complete: n\n };\n }\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */ catch(e) {\n return this._taskCompletionResolver.promise.catch(e);\n }\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */ then(e, t) {\n return this._taskCompletionResolver.promise.then(e, t);\n }\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */ _completeWith(e) {\n this._updateProgress(e), this._progressObserver.complete && this._progressObserver.complete(), \n this._taskCompletionResolver.resolve(e);\n }\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */ _failWith(e) {\n this._lastProgress.taskState = \"Error\", this._progressObserver.next && this._progressObserver.next(this._lastProgress), \n this._progressObserver.error && this._progressObserver.error(e), this._taskCompletionResolver.reject(e);\n }\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */ _updateProgress(e) {\n this._lastProgress = e, this._progressObserver.next && this._progressObserver.next(e);\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/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * {@link Firestore} instance.\n */ const Se = -1;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ class Firestore extends Firestore$1 {\n /** @hideconstructor */\n constructor(e, t, n, r) {\n super(e, t, n, r), \n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n this.type = \"firestore\", this._queue = new __PRIVATE_AsyncQueueImpl, this._persistenceKey = (null == r ? void 0 : r.name) || \"[DEFAULT]\";\n }\n async _terminate() {\n if (this._firestoreClient) {\n const e = this._firestoreClient.terminate();\n this._queue = new __PRIVATE_AsyncQueueImpl(e), this._firestoreClient = void 0, await e;\n }\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */ function initializeFirestore(e, t, n) {\n n || (n = \"(default)\");\n const r = _getProvider(e, \"firestore\");\n if (r.isInitialized(n)) {\n const e = r.getImmediate({\n identifier: n\n }), i = r.getOptions(n);\n if (deepEqual(i, t)) return e;\n throw new FirestoreError(D.FAILED_PRECONDITION, \"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.\");\n }\n if (void 0 !== t.cacheSizeBytes && void 0 !== t.localCache) throw new FirestoreError(D.INVALID_ARGUMENT, \"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object\");\n if (void 0 !== t.cacheSizeBytes && -1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new FirestoreError(D.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n return r.initialize({\n options: t,\n instanceIdentifier: n\n });\n}\n\nfunction getFirestore(t, n) {\n const r = \"object\" == typeof t ? t : getApp(), i = \"string\" == typeof t ? t : n || \"(default)\", s = _getProvider(r, \"firestore\").getImmediate({\n identifier: i\n });\n if (!s._initialized) {\n const e = getDefaultEmulatorHostnameAndPort(\"firestore\");\n e && connectFirestoreEmulator(s, ...e);\n }\n return s;\n}\n\n/**\n * @internal\n */ function ensureFirestoreConfigured(e) {\n if (e._terminated) throw new FirestoreError(D.FAILED_PRECONDITION, \"The client has already been terminated.\");\n return e._firestoreClient || __PRIVATE_configureFirestore(e), e._firestoreClient;\n}\n\nfunction __PRIVATE_configureFirestore(e) {\n var t, n, r;\n const i = e._freezeSettings(), s = function __PRIVATE_makeDatabaseInfo(e, t, n, r) {\n return new DatabaseInfo(e, t, n, r.host, r.ssl, r.experimentalForceLongPolling, r.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(r.experimentalLongPollingOptions), r.useFetchStreams);\n }(e._databaseId, (null === (t = e._app) || void 0 === t ? void 0 : t.options.appId) || \"\", e._persistenceKey, i);\n e._componentsProvider || (null === (n = i.localCache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (r = i.localCache) || void 0 === r ? void 0 : r._onlineComponentProvider) && (e._componentsProvider = {\n _offline: i.localCache._offlineComponentProvider,\n _online: i.localCache._onlineComponentProvider\n }), e._firestoreClient = new FirestoreClient(e._authCredentials, e._appCheckCredentials, e._queue, s, e._componentsProvider && function __PRIVATE_buildComponentProvider(e) {\n const t = null == e ? void 0 : e._online.build();\n return {\n _offline: null == e ? void 0 : e._offline.build(t),\n _online: t\n };\n }\n /**\n * Attempts to enable persistent storage, if possible.\n *\n * On failure, `enableIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * Note: `enableIndexedDbPersistence()` must be called before any other functions\n * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */ (e._componentsProvider));\n}\n\nfunction enableIndexedDbPersistence(e, t) {\n __PRIVATE_logWarn(\"enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.\");\n const n = e._freezeSettings();\n return __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, {\n build: e => new __PRIVATE_IndexedDbOfflineComponentProvider(e, n.cacheSizeBytes, null == t ? void 0 : t.forceOwnership)\n }), Promise.resolve();\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */ async function enableMultiTabIndexedDbPersistence(e) {\n __PRIVATE_logWarn(\"enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.\");\n const t = e._freezeSettings();\n __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, {\n build: e => new __PRIVATE_MultiTabOfflineComponentProvider(e, t.cacheSizeBytes)\n });\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */ function __PRIVATE_setPersistenceProviders(e, t, n) {\n if ((e = __PRIVATE_cast(e, Firestore))._firestoreClient || e._terminated) throw new FirestoreError(D.FAILED_PRECONDITION, \"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.\");\n if (e._componentsProvider || e._getSettings().localCache) throw new FirestoreError(D.FAILED_PRECONDITION, \"SDK cache is already specified.\");\n e._componentsProvider = {\n _online: t,\n _offline: n\n }, __PRIVATE_configureFirestore(e);\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */ function clearIndexedDbPersistence(e) {\n if (e._initialized && !e._terminated) throw new FirestoreError(D.FAILED_PRECONDITION, \"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.\");\n const t = new __PRIVATE_Deferred;\n return e._queue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n await async function __PRIVATE_indexedDbClearPersistence(e) {\n if (!__PRIVATE_SimpleDb.D()) return Promise.resolve();\n const t = e + \"main\";\n await __PRIVATE_SimpleDb.delete(t);\n }(__PRIVATE_indexedDbStoragePrefix(e._databaseId, e._persistenceKey)), t.resolve();\n } catch (e) {\n t.reject(e);\n }\n })), t.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */ function waitForPendingWrites(e) {\n return function __PRIVATE_firestoreClientWaitForPendingWrites(e) {\n const t = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e), t))), \n t.promise;\n }(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */ function enableNetwork(e) {\n return __PRIVATE_firestoreClientEnableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */ function disableNetwork(e) {\n return __PRIVATE_firestoreClientDisableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */ function terminate(e) {\n return _removeServiceInstance(e.app, \"firestore\", e._databaseId.database), e._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise`.\n */ function loadBundle(e, t) {\n const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), r = new LoadBundleTask;\n return __PRIVATE_firestoreClientLoadBundle(n, e._databaseId, t, r), r;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */ function namedQuery(e, t) {\n return __PRIVATE_firestoreClientGetNamedQuery(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), t).then((t => t ? new Query(e, null, t.query) : 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/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nclass AggregateField {\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(e = \"count\", t) {\n this._internalFieldPath = t, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateField\", this.aggregateType = e;\n }\n}\n\n/**\n * The results of executing an aggregation query.\n */ class AggregateQuerySnapshot {\n /** @hideconstructor */\n constructor(e, t, n) {\n this._userDataWriter = t, this._data = n, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateQuerySnapshot\", this.query = e;\n }\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */ data() {\n return this._userDataWriter.convertObjectMap(this._data);\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/**\n * An immutable object representing an array of bytes.\n */ class Bytes {\n /** @hideconstructor */\n constructor(e) {\n this._byteString = e;\n }\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */ static fromBase64String(e) {\n try {\n return new Bytes(ByteString.fromBase64String(e));\n } catch (e) {\n throw new FirestoreError(D.INVALID_ARGUMENT, \"Failed to construct data from Base64 string: \" + e);\n }\n }\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */ static fromUint8Array(e) {\n return new Bytes(ByteString.fromUint8Array(e));\n }\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */ toBase64() {\n return this._byteString.toBase64();\n }\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */ toUint8Array() {\n return this._byteString.toUint8Array();\n }\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */ toString() {\n return \"Bytes(base64: \" + this.toBase64() + \")\";\n }\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */ isEqual(e) {\n return this._byteString.isEqual(e._byteString);\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/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */ class FieldPath {\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...e) {\n for (let t = 0; t < e.length; ++t) if (0 === e[t].length) throw new FirestoreError(D.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). Field names must not be empty.\");\n this._internalPath = new FieldPath$1(e);\n }\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */ isEqual(e) {\n return this._internalPath.isEqual(e._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */ function documentId() {\n return new FieldPath(\"__name__\");\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 * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */ class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(e) {\n this._methodName = e;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */ class GeoPoint {\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(e, t) {\n if (!isFinite(e) || e < -90 || e > 90) throw new FirestoreError(D.INVALID_ARGUMENT, \"Latitude must be a number between -90 and 90, but was: \" + e);\n if (!isFinite(t) || t < -180 || t > 180) throw new FirestoreError(D.INVALID_ARGUMENT, \"Longitude must be a number between -180 and 180, but was: \" + t);\n this._lat = e, this._long = t;\n }\n /**\n * The latitude of this `GeoPoint` instance.\n */ get latitude() {\n return this._lat;\n }\n /**\n * The longitude of this `GeoPoint` instance.\n */ get longitude() {\n return this._long;\n }\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */ isEqual(e) {\n return this._lat === e._lat && this._long === e._long;\n }\n /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */ _compareTo(e) {\n return __PRIVATE_primitiveComparator(this._lat, e._lat) || __PRIVATE_primitiveComparator(this._long, e._long);\n }\n}\n\n/**\n * @license\n * Copyright 2024 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 * Represents a vector type in Firestore documents.\n * Create an instance with {@link FieldValue.vector}.\n *\n * @class VectorValue\n */ class VectorValue {\n /**\n * @private\n * @internal\n */\n constructor(e) {\n // Making a copy of the parameter.\n this._values = (e || []).map((e => e));\n }\n /**\n * Returns a copy of the raw number array form of the vector.\n */ toArray() {\n return this._values.map((e => e));\n }\n /**\n * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise.\n */ isEqual(e) {\n return function __PRIVATE_isPrimitiveArrayEqual(e, t) {\n if (e.length !== t.length) return !1;\n for (let n = 0; n < e.length; ++n) if (e[n] !== t[n]) return !1;\n return !0;\n }(this._values, e._values);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const be = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData {\n constructor(e, t, n) {\n this.data = e, this.fieldMask = t, this.fieldTransforms = n;\n }\n toMutation(e, t) {\n return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms) : new __PRIVATE_SetMutation(e, this.data, t, this.fieldTransforms);\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */ class ParsedUpdateData {\n constructor(e, \n // The fieldMask does not include document transforms.\n t, n) {\n this.data = e, this.fieldMask = t, this.fieldTransforms = n;\n }\n toMutation(e, t) {\n return new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms);\n }\n}\n\nfunction __PRIVATE_isWrite(e) {\n switch (e) {\n case 0 /* UserDataSource.Set */ :\n // fall through\n case 2 /* UserDataSource.MergeSet */ :\n // fall through\n case 1 /* UserDataSource.Update */ :\n return !0;\n\n case 3 /* UserDataSource.Argument */ :\n case 4 /* UserDataSource.ArrayArgument */ :\n return !1;\n\n default:\n throw fail();\n }\n}\n\n/** A \"context\" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(e, t, n, r, i, s) {\n this.settings = e, this.databaseId = t, this.serializer = n, this.ignoreUndefinedProperties = r, \n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n void 0 === i && this.vu(), this.fieldTransforms = i || [], this.fieldMask = s || [];\n }\n get path() {\n return this.settings.path;\n }\n get Cu() {\n return this.settings.Cu;\n }\n /** Returns a new context with the specified settings overwritten. */ Fu(e) {\n return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({}, this.settings), e), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);\n }\n Mu(e) {\n var t;\n const n = null === (t = this.path) || void 0 === t ? void 0 : t.child(e), r = this.Fu({\n path: n,\n xu: !1\n });\n return r.Ou(e), r;\n }\n Nu(e) {\n var t;\n const n = null === (t = this.path) || void 0 === t ? void 0 : t.child(e), r = this.Fu({\n path: n,\n xu: !1\n });\n return r.vu(), r;\n }\n Lu(e) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.Fu({\n path: void 0,\n xu: !0\n });\n }\n Bu(e) {\n return __PRIVATE_createError(e, this.settings.methodName, this.settings.ku || !1, this.path, this.settings.qu);\n }\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(e) {\n return void 0 !== this.fieldMask.find((t => e.isPrefixOf(t))) || void 0 !== this.fieldTransforms.find((t => e.isPrefixOf(t.field)));\n }\n vu() {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path) for (let e = 0; e < this.path.length; e++) this.Ou(this.path.get(e));\n }\n Ou(e) {\n if (0 === e.length) throw this.Bu(\"Document fields must not be empty\");\n if (__PRIVATE_isWrite(this.Cu) && be.test(e)) throw this.Bu('Document fields cannot begin and end with \"__\"');\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */ class __PRIVATE_UserDataReader {\n constructor(e, t, n) {\n this.databaseId = e, this.ignoreUndefinedProperties = t, this.serializer = n || __PRIVATE_newSerializer(e);\n }\n /** Creates a new top-level parse context. */ Qu(e, t, n, r = !1) {\n return new __PRIVATE_ParseContextImpl({\n Cu: e,\n methodName: t,\n qu: n,\n path: FieldPath$1.emptyPath(),\n xu: !1,\n ku: r\n }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);\n }\n}\n\nfunction __PRIVATE_newUserDataReader(e) {\n const t = e._freezeSettings(), n = __PRIVATE_newSerializer(e._databaseId);\n return new __PRIVATE_UserDataReader(e._databaseId, !!t.ignoreUndefinedProperties, n);\n}\n\n/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(e, t, n, r, i, s = {}) {\n const o = e.Qu(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , t, n, i);\n __PRIVATE_validatePlainObject(\"Data must be an object, but it was:\", o, r);\n const _ = __PRIVATE_parseObject(r, o);\n let a, u;\n if (s.merge) a = new FieldMask(o.fieldMask), u = o.fieldTransforms; else if (s.mergeFields) {\n const e = [];\n for (const r of s.mergeFields) {\n const i = __PRIVATE_fieldPathFromArgument$1(t, r, n);\n if (!o.contains(i)) throw new FirestoreError(D.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);\n __PRIVATE_fieldMaskContains(e, i) || e.push(i);\n }\n a = new FieldMask(e), u = o.fieldTransforms.filter((e => a.covers(e.field)));\n } else a = null, u = o.fieldTransforms;\n return new ParsedSetData(new ObjectValue(_), a, u);\n}\n\nclass __PRIVATE_DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(e) {\n if (2 /* UserDataSource.MergeSet */ !== e.Cu) throw 1 /* UserDataSource.Update */ === e.Cu ? e.Bu(`${this._methodName}() can only appear at the top level of your update data`) : e.Bu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n return e.fieldMask.push(e.path), null;\n }\n isEqual(e) {\n return e instanceof __PRIVATE_DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */ function __PRIVATE_createSentinelChildContext(e, t, n) {\n return new __PRIVATE_ParseContextImpl({\n Cu: 3 /* UserDataSource.Argument */ ,\n qu: t.settings.qu,\n methodName: e._methodName,\n xu: n\n }, t.databaseId, t.serializer, t.ignoreUndefinedProperties);\n}\n\nclass __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(e) {\n return new FieldTransform(e.path, new __PRIVATE_ServerTimestampTransform);\n }\n isEqual(e) {\n return e instanceof __PRIVATE_ServerTimestampFieldValueImpl;\n }\n}\n\nclass __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue {\n constructor(e, t) {\n super(e), this.Ku = t;\n }\n _toFieldTransform(e) {\n const t = __PRIVATE_createSentinelChildContext(this, e, \n /*array=*/ !0), n = this.Ku.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayUnionTransformOperation(n);\n return new FieldTransform(e.path, r);\n }\n isEqual(e) {\n return e instanceof __PRIVATE_ArrayUnionFieldValueImpl && deepEqual(this.Ku, e.Ku);\n }\n}\n\nclass __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(e, t) {\n super(e), this.Ku = t;\n }\n _toFieldTransform(e) {\n const t = __PRIVATE_createSentinelChildContext(this, e, \n /*array=*/ !0), n = this.Ku.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayRemoveTransformOperation(n);\n return new FieldTransform(e.path, r);\n }\n isEqual(e) {\n return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl && deepEqual(this.Ku, e.Ku);\n }\n}\n\nclass __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue {\n constructor(e, t) {\n super(e), this.$u = t;\n }\n _toFieldTransform(e) {\n const t = new __PRIVATE_NumericIncrementTransformOperation(e.serializer, toNumber(e.serializer, this.$u));\n return new FieldTransform(e.path, t);\n }\n isEqual(e) {\n return e instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.$u === e.$u;\n }\n}\n\n/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(e, t, n, r) {\n const i = e.Qu(1 /* UserDataSource.Update */ , t, n);\n __PRIVATE_validatePlainObject(\"Data must be an object, but it was:\", i, r);\n const s = [], o = ObjectValue.empty();\n forEach(r, ((e, r) => {\n const _ = __PRIVATE_fieldPathFromDotSeparatedString(t, e, n);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n r = getModularInstance(r);\n const a = i.Nu(_);\n if (r instanceof __PRIVATE_DeleteFieldValueImpl) \n // Add it to the field mask, but don't add anything to updateData.\n s.push(_); else {\n const e = __PRIVATE_parseData(r, a);\n null != e && (s.push(_), o.set(_, e));\n }\n }));\n const _ = new FieldMask(s);\n return new ParsedUpdateData(o, _, i.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(e, t, n, r, i, s) {\n const o = e.Qu(1 /* UserDataSource.Update */ , t, n), _ = [ __PRIVATE_fieldPathFromArgument$1(t, r, n) ], a = [ i ];\n if (s.length % 2 != 0) throw new FirestoreError(D.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);\n for (let e = 0; e < s.length; e += 2) _.push(__PRIVATE_fieldPathFromArgument$1(t, s[e])), \n a.push(s[e + 1]);\n const u = [], c = ObjectValue.empty();\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let e = _.length - 1; e >= 0; --e) if (!__PRIVATE_fieldMaskContains(u, _[e])) {\n const t = _[e];\n let n = a[e];\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n n = getModularInstance(n);\n const r = o.Nu(t);\n if (n instanceof __PRIVATE_DeleteFieldValueImpl) \n // Add it to the field mask, but don't add anything to updateData.\n u.push(t); else {\n const e = __PRIVATE_parseData(n, r);\n null != e && (u.push(t), c.set(t, e));\n }\n }\n const l = new FieldMask(u);\n return new ParsedUpdateData(c, l, o.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */ function __PRIVATE_parseQueryValue(e, t, n, r = !1) {\n return __PRIVATE_parseData(n, e.Qu(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , t));\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */ function __PRIVATE_parseData(e, t) {\n if (__PRIVATE_looksLikeJsonObject(\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n e = getModularInstance(e))) return __PRIVATE_validatePlainObject(\"Unsupported field value:\", t, e), \n __PRIVATE_parseObject(e, t);\n if (e instanceof FieldValue) \n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n return function __PRIVATE_parseSentinelFieldValue(e, t) {\n // Sentinels are only supported with writes, and not within arrays.\n if (!__PRIVATE_isWrite(t.Cu)) throw t.Bu(`${e._methodName}() can only be used with update() and set()`);\n if (!t.path) throw t.Bu(`${e._methodName}() is not currently supported inside arrays`);\n const n = e._toFieldTransform(t);\n n && t.fieldTransforms.push(n);\n }\n /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */ (e, t), null;\n if (void 0 === e && t.ignoreUndefinedProperties) \n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n if (\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n t.path && t.fieldMask.push(t.path), e instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (t.settings.xu && 4 /* UserDataSource.ArrayArgument */ !== t.Cu) throw t.Bu(\"Nested arrays are not supported\");\n return function __PRIVATE_parseArray(e, t) {\n const n = [];\n let r = 0;\n for (const i of e) {\n let e = __PRIVATE_parseData(i, t.Lu(r));\n null == e && (\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n e = {\n nullValue: \"NULL_VALUE\"\n }), n.push(e), r++;\n }\n return {\n arrayValue: {\n values: n\n }\n };\n }(e, t);\n }\n return function __PRIVATE_parseScalarValue(e, t) {\n if (null === (e = getModularInstance(e))) return {\n nullValue: \"NULL_VALUE\"\n };\n if (\"number\" == typeof e) return toNumber(t.serializer, e);\n if (\"boolean\" == typeof e) return {\n booleanValue: e\n };\n if (\"string\" == typeof e) return {\n stringValue: e\n };\n if (e instanceof Date) {\n const n = Timestamp.fromDate(e);\n return {\n timestampValue: toTimestamp(t.serializer, n)\n };\n }\n if (e instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const n = new Timestamp(e.seconds, 1e3 * Math.floor(e.nanoseconds / 1e3));\n return {\n timestampValue: toTimestamp(t.serializer, n)\n };\n }\n if (e instanceof GeoPoint) return {\n geoPointValue: {\n latitude: e.latitude,\n longitude: e.longitude\n }\n };\n if (e instanceof Bytes) return {\n bytesValue: __PRIVATE_toBytes(t.serializer, e._byteString)\n };\n if (e instanceof DocumentReference) {\n const n = t.databaseId, r = e.firestore._databaseId;\n if (!r.isEqual(n)) throw t.Bu(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);\n return {\n referenceValue: __PRIVATE_toResourceName(e.firestore._databaseId || t.databaseId, e._key.path)\n };\n }\n if (e instanceof VectorValue) \n /**\n * Creates a new VectorValue proto value (using the internal format).\n */\n return function __PRIVATE_parseVectorValue(e, t) {\n return {\n mapValue: {\n fields: {\n __type__: {\n stringValue: \"__vector__\"\n },\n value: {\n arrayValue: {\n values: e.toArray().map((e => {\n if (\"number\" != typeof e) throw t.Bu(\"VectorValues must only contain numeric values.\");\n return __PRIVATE_toDouble(t.serializer, e);\n }))\n }\n }\n }\n }\n };\n }\n /**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */ (e, t);\n throw t.Bu(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`);\n }(e, t);\n}\n\nfunction __PRIVATE_parseObject(e, t) {\n const n = {};\n return isEmpty(e) ? \n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n t.path && t.path.length > 0 && t.fieldMask.push(t.path) : forEach(e, ((e, r) => {\n const i = __PRIVATE_parseData(r, t.Mu(e));\n null != i && (n[e] = i);\n })), {\n mapValue: {\n fields: n\n }\n };\n}\n\nfunction __PRIVATE_looksLikeJsonObject(e) {\n return !(\"object\" != typeof e || null === e || e instanceof Array || e instanceof Date || e instanceof Timestamp || e instanceof GeoPoint || e instanceof Bytes || e instanceof DocumentReference || e instanceof FieldValue || e instanceof VectorValue);\n}\n\nfunction __PRIVATE_validatePlainObject(e, t, n) {\n if (!__PRIVATE_looksLikeJsonObject(n) || !function __PRIVATE_isPlainObject(e) {\n return \"object\" == typeof e && null !== e && (Object.getPrototypeOf(e) === Object.prototype || null === Object.getPrototypeOf(e));\n }(n)) {\n const r = __PRIVATE_valueDescription(n);\n throw \"an object\" === r ? t.Bu(e + \" a custom object\") : t.Bu(e + \" \" + r);\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */ function __PRIVATE_fieldPathFromArgument$1(e, t, n) {\n if ((\n // If required, replace the FieldPath Compat class with the firestore-exp\n // FieldPath.\n t = getModularInstance(t)) instanceof FieldPath) return t._internalPath;\n if (\"string\" == typeof t) return __PRIVATE_fieldPathFromDotSeparatedString(e, t);\n throw __PRIVATE_createError(\"Field path arguments must be of type string or \", e, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */ const De = new RegExp(\"[~\\\\*/\\\\[\\\\]]\");\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */ function __PRIVATE_fieldPathFromDotSeparatedString(e, t, n) {\n if (t.search(De) >= 0) throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`, e, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n try {\n return new FieldPath(...t.split(\".\"))._internalPath;\n } catch (r) {\n throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, e, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n }\n}\n\nfunction __PRIVATE_createError(e, t, n, r, i) {\n const s = r && !r.isEmpty(), o = void 0 !== i;\n let _ = `Function ${t}() called with invalid data`;\n n && (_ += \" (via `toFirestore()`)\"), _ += \". \";\n let a = \"\";\n return (s || o) && (a += \" (found\", s && (a += ` in field ${r}`), o && (a += ` in document ${i}`), \n a += \")\"), new FirestoreError(D.INVALID_ARGUMENT, _ + e + a);\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(e, t) {\n return e.some((e => e.isEqual(t)));\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 * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class DocumentSnapshot$1 {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n /** @hideconstructor protected */\n constructor(e, t, n, r, i) {\n this._firestore = e, this._userDataWriter = t, this._key = n, this._document = r, \n this._converter = i;\n }\n /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */ get ref() {\n return new DocumentReference(this._firestore, this._converter, this._key);\n }\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */ exists() {\n return null !== this._document;\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */ data() {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const e = new QueryDocumentSnapshot$1(this._firestore, this._userDataWriter, this._key, this._document, \n /* converter= */ null);\n return this._converter.fromFirestore(e);\n }\n return this._userDataWriter.convertValue(this._document.data.value);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(e) {\n if (this._document) {\n const t = this._document.data.field(__PRIVATE_fieldPathFromArgument(\"DocumentSnapshot.get\", e));\n if (null !== t) return this._userDataWriter.convertValue(t);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data() {\n return super.data();\n }\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */ function __PRIVATE_fieldPathFromArgument(e, t) {\n return \"string\" == typeof t ? __PRIVATE_fieldPathFromDotSeparatedString(e, t) : t instanceof FieldPath ? t._internalPath : t._delegate._internalPath;\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 */ function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e) {\n if (\"L\" /* LimitType.Last */ === e.limitType && 0 === e.explicitOrderBy.length) throw new FirestoreError(D.UNIMPLEMENTED, \"limitToLast() queries require specifying at least one orderBy() clause\");\n}\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */ class AppliableConstraint {}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */ class QueryConstraint extends AppliableConstraint {}\n\nfunction query(e, t, ...n) {\n let r = [];\n t instanceof AppliableConstraint && r.push(t), r = r.concat(n), function __PRIVATE_validateQueryConstraintArray(e) {\n const t = e.filter((e => e instanceof QueryCompositeFilterConstraint)).length, n = e.filter((e => e instanceof QueryFieldFilterConstraint)).length;\n if (t > 1 || t > 0 && n > 0) throw new FirestoreError(D.INVALID_ARGUMENT, \"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.\");\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 * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */ (r);\n for (const t of r) e = t._apply(e);\n return e;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */ class QueryFieldFilterConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(e, t, n) {\n super(), this._field = e, this._op = t, this._value = n, \n /** The type of this query constraint */\n this.type = \"where\";\n }\n static _create(e, t, n) {\n return new QueryFieldFilterConstraint(e, t, n);\n }\n _apply(e) {\n const t = this._parse(e);\n return __PRIVATE_validateNewFieldFilter(e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t));\n }\n _parse(e) {\n const t = __PRIVATE_newUserDataReader(e.firestore), n = function __PRIVATE_newQueryFilter(e, t, n, r, i, s, o) {\n let _;\n if (i.isKeyField()) {\n if (\"array-contains\" /* Operator.ARRAY_CONTAINS */ === s || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid Query. You can't perform '${s}' queries on documentId().`);\n if (\"in\" /* Operator.IN */ === s || \"not-in\" /* Operator.NOT_IN */ === s) {\n __PRIVATE_validateDisjunctiveFilterElements(o, s);\n const t = [];\n for (const n of o) t.push(__PRIVATE_parseDocumentIdValue(r, e, n));\n _ = {\n arrayValue: {\n values: t\n }\n };\n } else _ = __PRIVATE_parseDocumentIdValue(r, e, o);\n } else \"in\" /* Operator.IN */ !== s && \"not-in\" /* Operator.NOT_IN */ !== s && \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), \n _ = __PRIVATE_parseQueryValue(n, t, o, \n /* allowArrays= */ \"in\" /* Operator.IN */ === s || \"not-in\" /* Operator.NOT_IN */ === s);\n return FieldFilter.create(i, s, _);\n }(e._query, \"where\", t, e.firestore._databaseId, this._field, this._op, this._value);\n return n;\n }\n}\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */ function where(e, t, n) {\n const r = t, i = __PRIVATE_fieldPathFromArgument(\"where\", e);\n return QueryFieldFilterConstraint._create(i, r, n);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */ class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n e, t) {\n super(), this.type = e, this._queryConstraints = t;\n }\n static _create(e, t) {\n return new QueryCompositeFilterConstraint(e, t);\n }\n _parse(e) {\n const t = this._queryConstraints.map((t => t._parse(e))).filter((e => e.getFilters().length > 0));\n return 1 === t.length ? t[0] : CompositeFilter.create(t, this._getOperator());\n }\n _apply(e) {\n const t = this._parse(e);\n return 0 === t.getFilters().length ? e : (function __PRIVATE_validateNewFilter(e, t) {\n let n = e;\n const r = t.getFlattenedFilters();\n for (const e of r) __PRIVATE_validateNewFieldFilter(n, e), n = __PRIVATE_queryWithAddedFilter(n, e);\n }\n // Checks if any of the provided filter operators are included in the given list of filters and\n // returns the first one that is, or null if none are.\n (e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t)));\n }\n _getQueryConstraints() {\n return this._queryConstraints;\n }\n _getOperator() {\n return \"and\" === this.type ? \"and\" /* CompositeOperator.AND */ : \"or\" /* CompositeOperator.OR */;\n }\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */ function or(...e) {\n // Only support QueryFilterConstraints\n return e.forEach((e => __PRIVATE_validateQueryFilterConstraint(\"or\", e))), QueryCompositeFilterConstraint._create(\"or\" /* CompositeOperator.OR */ , e);\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */ function and(...e) {\n // Only support QueryFilterConstraints\n return e.forEach((e => __PRIVATE_validateQueryFilterConstraint(\"and\", e))), QueryCompositeFilterConstraint._create(\"and\" /* CompositeOperator.AND */ , e);\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */ class QueryOrderByConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(e, t) {\n super(), this._field = e, this._direction = t, \n /** The type of this query constraint */\n this.type = \"orderBy\";\n }\n static _create(e, t) {\n return new QueryOrderByConstraint(e, t);\n }\n _apply(e) {\n const t = function __PRIVATE_newQueryOrderBy(e, t, n) {\n if (null !== e.startAt) throw new FirestoreError(D.INVALID_ARGUMENT, \"Invalid query. You must not call startAt() or startAfter() before calling orderBy().\");\n if (null !== e.endAt) throw new FirestoreError(D.INVALID_ARGUMENT, \"Invalid query. You must not call endAt() or endBefore() before calling orderBy().\");\n return new OrderBy(t, n);\n }\n /**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */ (e._query, this._field, this._direction);\n return new Query(e.firestore, e.converter, function __PRIVATE_queryWithAddedOrderBy(e, t) {\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const n = e.explicitOrderBy.concat([ t ]);\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, n, e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);\n }(e._query, t));\n }\n}\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */ function orderBy(e, t = \"asc\") {\n const n = t, r = __PRIVATE_fieldPathFromArgument(\"orderBy\", e);\n return QueryOrderByConstraint._create(r, n);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */ class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n e, t, n) {\n super(), this.type = e, this._limit = t, this._limitType = n;\n }\n static _create(e, t, n) {\n return new QueryLimitConstraint(e, t, n);\n }\n _apply(e) {\n return new Query(e.firestore, e.converter, __PRIVATE_queryWithLimit(e._query, this._limit, this._limitType));\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function limit(e) {\n return __PRIVATE_validatePositiveNumber(\"limit\", e), QueryLimitConstraint._create(\"limit\", e, \"F\" /* LimitType.First */);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function limitToLast(e) {\n return __PRIVATE_validatePositiveNumber(\"limitToLast\", e), QueryLimitConstraint._create(\"limitToLast\", e, \"L\" /* LimitType.Last */);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */ class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n e, t, n) {\n super(), this.type = e, this._docOrFields = t, this._inclusive = n;\n }\n static _create(e, t, n) {\n return new QueryStartAtConstraint(e, t, n);\n }\n _apply(e) {\n const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive);\n return new Query(e.firestore, e.converter, function __PRIVATE_queryWithStartAt(e, t) {\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, t, e.endAt);\n }(e._query, t));\n }\n}\n\nfunction startAt(...e) {\n return QueryStartAtConstraint._create(\"startAt\", e, \n /*inclusive=*/ !0);\n}\n\nfunction startAfter(...e) {\n return QueryStartAtConstraint._create(\"startAfter\", e, \n /*inclusive=*/ !1);\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */ class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n e, t, n) {\n super(), this.type = e, this._docOrFields = t, this._inclusive = n;\n }\n static _create(e, t, n) {\n return new QueryEndAtConstraint(e, t, n);\n }\n _apply(e) {\n const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive);\n return new Query(e.firestore, e.converter, function __PRIVATE_queryWithEndAt(e, t) {\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, t);\n }(e._query, t));\n }\n}\n\nfunction endBefore(...e) {\n return QueryEndAtConstraint._create(\"endBefore\", e, \n /*inclusive=*/ !1);\n}\n\nfunction endAt(...e) {\n return QueryEndAtConstraint._create(\"endAt\", e, \n /*inclusive=*/ !0);\n}\n\n/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(e, t, n, r) {\n if (n[0] = getModularInstance(n[0]), n[0] instanceof DocumentSnapshot$1) return function __PRIVATE_newQueryBoundFromDocument(e, t, n, r, i) {\n if (!r) throw new FirestoreError(D.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);\n const s = [];\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const n of __PRIVATE_queryNormalizedOrderBy(e)) if (n.field.isKeyField()) s.push(__PRIVATE_refValue(t, r.key)); else {\n const e = r.data.field(n.field);\n if (__PRIVATE_isServerTimestamp(e)) throw new FirestoreError(D.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field \"' + n.field + '\" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');\n if (null === e) {\n const e = n.field.canonicalString();\n throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`);\n }\n s.push(e);\n }\n return new Bound(s, i);\n }\n /**\n * Converts a list of field values to a `Bound` for the given query.\n */ (e._query, e.firestore._databaseId, t, n[0]._document, r);\n {\n const i = __PRIVATE_newUserDataReader(e.firestore);\n return function __PRIVATE_newQueryBoundFromFields(e, t, n, r, i, s) {\n // Use explicit order by's because it has to match the query the user made\n const o = e.explicitOrderBy;\n if (i.length > o.length) throw new FirestoreError(D.INVALID_ARGUMENT, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);\n const _ = [];\n for (let s = 0; s < i.length; s++) {\n const a = i[s];\n if (o[s].field.isKeyField()) {\n if (\"string\" != typeof a) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof a}`);\n if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== a.indexOf(\"/\")) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${a}' contains a slash.`);\n const n = e.path.child(ResourcePath.fromString(a));\n if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);\n const i = new DocumentKey(n);\n _.push(__PRIVATE_refValue(t, i));\n } else {\n const e = __PRIVATE_parseQueryValue(n, r, a);\n _.push(e);\n }\n }\n return new Bound(_, s);\n }\n /**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */ (e._query, e.firestore._databaseId, i, t, n, r);\n }\n}\n\nfunction __PRIVATE_parseDocumentIdValue(e, t, n) {\n if (\"string\" == typeof (n = getModularInstance(n))) {\n if (\"\" === n) throw new FirestoreError(D.INVALID_ARGUMENT, \"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.\");\n if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== n.indexOf(\"/\")) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);\n const r = t.path.child(ResourcePath.fromString(n));\n if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);\n return __PRIVATE_refValue(e, new DocumentKey(r));\n }\n if (n instanceof DocumentReference) return __PRIVATE_refValue(e, n._key);\n throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(n)}.`);\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */ function __PRIVATE_validateDisjunctiveFilterElements(e, t) {\n if (!Array.isArray(e) || 0 === e.length) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */ function __PRIVATE_validateNewFieldFilter(e, t) {\n const n = function __PRIVATE_findOpInsideFilters(e, t) {\n for (const n of e) for (const e of n.getFlattenedFilters()) if (t.indexOf(e.op) >= 0) return e.op;\n return null;\n }(e.filters, function __PRIVATE_conflictingOps(e) {\n switch (e) {\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return [ \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n case \"in\" /* Operator.IN */ :\n return [ \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"not-in\" /* Operator.NOT_IN */ :\n return [ \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ , \"!=\" /* Operator.NOT_EQUAL */ ];\n\n default:\n return [];\n }\n }(t.op));\n if (null !== n) \n // Special case when it's a duplicate op to give a slightly clearer error message.\n throw n === t.op ? new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${t.op.toString()}' filter.`) : new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`);\n}\n\nfunction __PRIVATE_validateQueryFilterConstraint(e, t) {\n if (!(t instanceof QueryFieldFilterConstraint || t instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(D.INVALID_ARGUMENT, `Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);\n}\n\nclass AbstractUserDataWriter {\n convertValue(e, t = \"none\") {\n switch (__PRIVATE_typeOrder(e)) {\n case 0 /* TypeOrder.NullValue */ :\n return null;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return e.booleanValue;\n\n case 2 /* TypeOrder.NumberValue */ :\n return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return this.convertTimestamp(e.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return this.convertServerTimestamp(e, t);\n\n case 5 /* TypeOrder.StringValue */ :\n return e.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));\n\n case 7 /* TypeOrder.RefValue */ :\n return this.convertReference(e.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return this.convertGeoPoint(e.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return this.convertArray(e.arrayValue, t);\n\n case 11 /* TypeOrder.ObjectValue */ :\n return this.convertObject(e.mapValue, t);\n\n case 10 /* TypeOrder.VectorValue */ :\n return this.convertVectorValue(e.mapValue);\n\n default:\n throw fail();\n }\n }\n convertObject(e, t) {\n return this.convertObjectMap(e.fields, t);\n }\n /**\n * @internal\n */ convertObjectMap(e, t = \"none\") {\n const n = {};\n return forEach(e, ((e, r) => {\n n[e] = this.convertValue(r, t);\n })), n;\n }\n /**\n * @internal\n */ convertVectorValue(e) {\n var t, n, r;\n const i = null === (r = null === (n = null === (t = e.fields) || void 0 === t ? void 0 : t.value.arrayValue) || void 0 === n ? void 0 : n.values) || void 0 === r ? void 0 : r.map((e => __PRIVATE_normalizeNumber(e.doubleValue)));\n return new VectorValue(i);\n }\n convertGeoPoint(e) {\n return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(e.longitude));\n }\n convertArray(e, t) {\n return (e.values || []).map((e => this.convertValue(e, t)));\n }\n convertServerTimestamp(e, t) {\n switch (t) {\n case \"previous\":\n const n = __PRIVATE_getPreviousValue(e);\n return null == n ? null : this.convertValue(n, t);\n\n case \"estimate\":\n return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));\n\n default:\n return null;\n }\n }\n convertTimestamp(e) {\n const t = __PRIVATE_normalizeTimestamp(e);\n return new Timestamp(t.seconds, t.nanos);\n }\n convertDocumentKey(e, t) {\n const n = ResourcePath.fromString(e);\n __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n));\n const r = new DatabaseId(n.get(1), n.get(3)), i = new DocumentKey(n.popFirst(5));\n return r.isEqual(t) || \n // TODO(b/64130202): Somehow support foreign references.\n __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`), \n i;\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/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */ function __PRIVATE_applyFirestoreDataConverter(e, t, n) {\n let r;\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return r = e ? n && (n.merge || n.mergeFields) ? e.toFirestore(t, n) : e.toFirestore(t) : t, \n r;\n}\n\nclass __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(e) {\n super(), this.firestore = e;\n }\n convertBytes(e) {\n return new Bytes(e);\n }\n convertReference(e) {\n const t = this.convertDocumentKey(e, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, t);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */ function sum(e) {\n return new AggregateField(\"sum\", __PRIVATE_fieldPathFromArgument$1(\"sum\", e));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */ function average(e) {\n return new AggregateField(\"avg\", __PRIVATE_fieldPathFromArgument$1(\"average\", e));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */ function count() {\n return new AggregateField(\"count\");\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */ function aggregateFieldEqual(e, t) {\n var n, r;\n return e instanceof AggregateField && t instanceof AggregateField && e.aggregateType === t.aggregateType && (null === (n = e._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (r = t._internalFieldPath) || void 0 === r ? void 0 : r.canonicalString());\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */ function aggregateQuerySnapshotEqual(e, t) {\n return queryEqual(e.query, t.query) && deepEqual(e.data(), t.data());\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 * Metadata about a snapshot, describing the state of the snapshot.\n */ class SnapshotMetadata {\n /** @hideconstructor */\n constructor(e, t) {\n this.hasPendingWrites = e, this.fromCache = t;\n }\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */ isEqual(e) {\n return this.hasPendingWrites === e.hasPendingWrites && this.fromCache === e.fromCache;\n }\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class DocumentSnapshot extends DocumentSnapshot$1 {\n /** @hideconstructor protected */\n constructor(e, t, n, r, i, s) {\n super(e, t, n, r, s), this._firestore = e, this._firestoreImpl = e, this.metadata = i;\n }\n /**\n * Returns whether or not the data exists. True if the document exists.\n */ exists() {\n return super.exists();\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */ data(e = {}) {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, \n /* converter= */ null);\n return this._converter.fromFirestore(t, e);\n }\n return this._userDataWriter.convertValue(this._document.data.value, e.serverTimestamps);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(e, t = {}) {\n if (this._document) {\n const n = this._document.data.field(__PRIVATE_fieldPathFromArgument(\"DocumentSnapshot.get\", e));\n if (null !== n) return this._userDataWriter.convertValue(n, t.serverTimestamps);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class QueryDocumentSnapshot extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(e = {}) {\n return super.data(e);\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */ class QuerySnapshot {\n /** @hideconstructor */\n constructor(e, t, n, r) {\n this._firestore = e, this._userDataWriter = t, this._snapshot = r, this.metadata = new SnapshotMetadata(r.hasPendingWrites, r.fromCache), \n this.query = n;\n }\n /** An array of all the documents in the `QuerySnapshot`. */ get docs() {\n const e = [];\n return this.forEach((t => e.push(t))), e;\n }\n /** The number of documents in the `QuerySnapshot`. */ get size() {\n return this._snapshot.docs.size;\n }\n /** True if there are no documents in the `QuerySnapshot`. */ get empty() {\n return 0 === this.size;\n }\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */ forEach(e, t) {\n this._snapshot.docs.forEach((n => {\n e.call(t, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, n.key, n, new SnapshotMetadata(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));\n }));\n }\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */ docChanges(e = {}) {\n const t = !!e.includeMetadataChanges;\n if (t && this._snapshot.excludesMetadataChanges) throw new FirestoreError(D.INVALID_ARGUMENT, \"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().\");\n return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === t || (this._cachedChanges = \n /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\n function __PRIVATE_changesFromSnapshot(e, t) {\n if (e._snapshot.oldDocs.isEmpty()) {\n let t = 0;\n return e._snapshot.docChanges.map((n => {\n const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, n.doc.key, n.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(n.doc.key), e._snapshot.fromCache), e.query.converter);\n return n.doc, {\n type: \"added\",\n doc: r,\n oldIndex: -1,\n newIndex: t++\n };\n }));\n }\n {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let n = e._snapshot.oldDocs;\n return e._snapshot.docChanges.filter((e => t || 3 /* ChangeType.Metadata */ !== e.type)).map((t => {\n const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, t.doc.key, t.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(t.doc.key), e._snapshot.fromCache), e.query.converter);\n let i = -1, s = -1;\n return 0 /* ChangeType.Added */ !== t.type && (i = n.indexOf(t.doc.key), n = n.delete(t.doc.key)), \n 1 /* ChangeType.Removed */ !== t.type && (n = n.add(t.doc), s = n.indexOf(t.doc.key)), \n {\n type: __PRIVATE_resultChangeType(t.type),\n doc: r,\n oldIndex: i,\n newIndex: s\n };\n }));\n }\n }(this, t), this._cachedChangesIncludeMetadataChanges = t), this._cachedChanges;\n }\n}\n\nfunction __PRIVATE_resultChangeType(e) {\n switch (e) {\n case 0 /* ChangeType.Added */ :\n return \"added\";\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n return \"modified\";\n\n case 1 /* ChangeType.Removed */ :\n return \"removed\";\n\n default:\n return fail();\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */ function snapshotEqual(e, t) {\n return e instanceof DocumentSnapshot && t instanceof DocumentSnapshot ? e._firestore === t._firestore && e._key.isEqual(t._key) && (null === e._document ? null === t._document : e._document.isEqual(t._document)) && e._converter === t._converter : e instanceof QuerySnapshot && t instanceof QuerySnapshot && (e._firestore === t._firestore && queryEqual(e.query, t.query) && e.metadata.isEqual(t.metadata) && e._snapshot.isEqual(t._snapshot));\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 * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDoc(e) {\n e = __PRIVATE_cast(e, DocumentReference);\n const t = __PRIVATE_cast(e.firestore, Firestore);\n return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key).then((n => __PRIVATE_convertToDocSnapshot(t, e, n)));\n}\n\nclass __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter {\n constructor(e) {\n super(), this.firestore = e;\n }\n convertBytes(e) {\n return new Bytes(e);\n }\n convertReference(e) {\n const t = this.convertDocumentKey(e, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, t);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDocFromCache(e) {\n e = __PRIVATE_cast(e, DocumentReference);\n const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n return __PRIVATE_firestoreClientGetDocumentFromLocalCache(n, e._key).then((n => new DocumentSnapshot(t, r, e._key, n, new SnapshotMetadata(null !== n && n.hasLocalMutations, \n /* fromCache= */ !0), e.converter)));\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDocFromServer(e) {\n e = __PRIVATE_cast(e, DocumentReference);\n const t = __PRIVATE_cast(e.firestore, Firestore);\n return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key, {\n source: \"server\"\n }).then((n => __PRIVATE_convertToDocSnapshot(t, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocs(e) {\n e = __PRIVATE_cast(e, Query);\n const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query), __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocsFromCache(e) {\n e = __PRIVATE_cast(e, Query);\n const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n return __PRIVATE_firestoreClientGetDocumentsFromLocalCache(n, e._query).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocsFromServer(e) {\n e = __PRIVATE_cast(e, Query);\n const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query, {\n source: \"server\"\n }).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\nfunction setDoc(e, t, n) {\n e = __PRIVATE_cast(e, DocumentReference);\n const r = __PRIVATE_cast(e.firestore, Firestore), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t, n);\n return executeWrite(r, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(r), \"setDoc\", e._key, i, null !== e.converter, n).toMutation(e._key, Precondition.none()) ]);\n}\n\nfunction updateDoc(e, t, n, ...r) {\n e = __PRIVATE_cast(e, DocumentReference);\n const i = __PRIVATE_cast(e.firestore, Firestore), s = __PRIVATE_newUserDataReader(i);\n let o;\n o = \"string\" == typeof (\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(s, \"updateDoc\", e._key, t, n, r) : __PRIVATE_parseUpdateData(s, \"updateDoc\", e._key, t);\n return executeWrite(i, [ o.toMutation(e._key, Precondition.exists(!0)) ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */ function deleteDoc(e) {\n return executeWrite(__PRIVATE_cast(e.firestore, Firestore), [ new __PRIVATE_DeleteMutation(e._key, Precondition.none()) ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */ function addDoc(e, t) {\n const n = __PRIVATE_cast(e.firestore, Firestore), r = doc(e), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t);\n return executeWrite(n, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore), \"addDoc\", r._key, i, null !== e.converter, {}).toMutation(r._key, Precondition.exists(!1)) ]).then((() => r));\n}\n\nfunction onSnapshot(e, ...t) {\n var n, r, i;\n e = getModularInstance(e);\n let s = {\n includeMetadataChanges: !1,\n source: \"default\"\n }, o = 0;\n \"object\" != typeof t[o] || __PRIVATE_isPartialObserver(t[o]) || (s = t[o], o++);\n const _ = {\n includeMetadataChanges: s.includeMetadataChanges,\n source: s.source\n };\n if (__PRIVATE_isPartialObserver(t[o])) {\n const e = t[o];\n t[o] = null === (n = e.next) || void 0 === n ? void 0 : n.bind(e), t[o + 1] = null === (r = e.error) || void 0 === r ? void 0 : r.bind(e), \n t[o + 2] = null === (i = e.complete) || void 0 === i ? void 0 : i.bind(e);\n }\n let a, u, c;\n if (e instanceof DocumentReference) u = __PRIVATE_cast(e.firestore, Firestore), \n c = __PRIVATE_newQueryForPath(e._key.path), a = {\n next: n => {\n t[o] && t[o](__PRIVATE_convertToDocSnapshot(u, e, n));\n },\n error: t[o + 1],\n complete: t[o + 2]\n }; else {\n const n = __PRIVATE_cast(e, Query);\n u = __PRIVATE_cast(n.firestore, Firestore), c = n._query;\n const r = new __PRIVATE_ExpUserDataWriter(u);\n a = {\n next: e => {\n t[o] && t[o](new QuerySnapshot(u, r, n, e));\n },\n error: t[o + 1],\n complete: t[o + 2]\n }, __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query);\n }\n return function __PRIVATE_firestoreClientListen(e, t, n, r) {\n const i = new __PRIVATE_AsyncObserver(r), s = new __PRIVATE_QueryListener(t, i, n);\n return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e), s))), \n () => {\n i.Za(), e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e), s)));\n };\n }(ensureFirestoreConfigured(u), c, _, a);\n}\n\nfunction onSnapshotsInSync(e, t) {\n return __PRIVATE_firestoreClientAddSnapshotsInSyncListener(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), __PRIVATE_isPartialObserver(t) ? t : {\n next: t\n });\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */ function executeWrite(e, t) {\n return function __PRIVATE_firestoreClientWrite(e, t) {\n const n = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e), t, n))), \n n.promise;\n }(ensureFirestoreConfigured(e), t);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */ function __PRIVATE_convertToDocSnapshot(e, t, n) {\n const r = n.docs.get(t._key), i = new __PRIVATE_ExpUserDataWriter(e);\n return new DocumentSnapshot(e, i, t._key, r, new SnapshotMetadata(n.hasPendingWrites, n.fromCache), t.converter);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */ function getCountFromServer(e) {\n return getAggregateFromServer(e, {\n count: count()\n });\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */ function getAggregateFromServer(e, t) {\n const n = __PRIVATE_cast(e.firestore, Firestore), r = ensureFirestoreConfigured(n), i = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath)));\n // Run the aggregation and convert the results\n return __PRIVATE_firestoreClientRunAggregateQuery(r, e._query, i).then((t => \n /**\n * Converts the core aggregation result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\n function __PRIVATE_convertToAggregateQuerySnapshot(e, t, n) {\n const r = new __PRIVATE_ExpUserDataWriter(e);\n return new AggregateQuerySnapshot(t, r, n);\n }\n /**\n * @license\n * Copyright 2023 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, e, t)));\n}\n\nclass __PRIVATE_MemoryLocalCacheImpl {\n constructor(e) {\n this.kind = \"memory\", this._onlineComponentProvider = OnlineComponentProvider.provider, \n (null == e ? void 0 : e.garbageCollector) ? this._offlineComponentProvider = e.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = __PRIVATE_MemoryOfflineComponentProvider.provider;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass __PRIVATE_PersistentLocalCacheImpl {\n constructor(e) {\n let t;\n this.kind = \"persistent\", (null == e ? void 0 : e.tabManager) ? (e.tabManager._initialize(e), \n t = e.tabManager) : (t = persistentSingleTabManager(void 0), t._initialize(e)), \n this._onlineComponentProvider = t._onlineComponentProvider, this._offlineComponentProvider = t._offlineComponentProvider;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass __PRIVATE_MemoryEagerGarbageCollectorImpl {\n constructor() {\n this.kind = \"memoryEager\", this._offlineComponentProvider = __PRIVATE_MemoryOfflineComponentProvider.provider;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass __PRIVATE_MemoryLruGarbageCollectorImpl {\n constructor(e) {\n this.kind = \"memoryLru\", this._offlineComponentProvider = {\n build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(e)\n };\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */ function memoryEagerGarbageCollector() {\n return new __PRIVATE_MemoryEagerGarbageCollectorImpl;\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */ function memoryLruGarbageCollector(e) {\n return new __PRIVATE_MemoryLruGarbageCollectorImpl(null == e ? void 0 : e.cacheSizeBytes);\n}\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */ function memoryLocalCache(e) {\n return new __PRIVATE_MemoryLocalCacheImpl(e);\n}\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */ function persistentLocalCache(e) {\n return new __PRIVATE_PersistentLocalCacheImpl(e);\n}\n\nclass __PRIVATE_SingleTabManagerImpl {\n constructor(e) {\n this.forceOwnership = e, this.kind = \"persistentSingleTab\";\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n /**\n * @internal\n */ _initialize(e) {\n this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = {\n build: t => new __PRIVATE_IndexedDbOfflineComponentProvider(t, null == e ? void 0 : e.cacheSizeBytes, this.forceOwnership)\n };\n }\n}\n\nclass __PRIVATE_MultiTabManagerImpl {\n constructor() {\n this.kind = \"PersistentMultipleTab\";\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n /**\n * @internal\n */ _initialize(e) {\n this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = {\n build: t => new __PRIVATE_MultiTabOfflineComponentProvider(t, null == e ? void 0 : e.cacheSizeBytes)\n };\n }\n}\n\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */ function persistentSingleTabManager(e) {\n return new __PRIVATE_SingleTabManagerImpl(null == e ? void 0 : e.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */ function persistentMultipleTabManager() {\n return new __PRIVATE_MultiTabManagerImpl;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const ve = {\n maxAttempts: 5\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 * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nclass WriteBatch {\n /** @hideconstructor */\n constructor(e, t) {\n this._firestore = e, this._commitHandler = t, this._mutations = [], this._committed = !1, \n this._dataReader = __PRIVATE_newUserDataReader(e);\n }\n set(e, t, n) {\n this._verifyNotCommitted();\n const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, \"WriteBatch.set\", r._key, i, null !== r.converter, n);\n return this._mutations.push(s.toMutation(r._key, Precondition.none())), this;\n }\n update(e, t, n, ...r) {\n this._verifyNotCommitted();\n const i = __PRIVATE_validateReference(e, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let s;\n return s = \"string\" == typeof (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, \"WriteBatch.update\", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, \"WriteBatch.update\", i._key, t), \n this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */ delete(e) {\n this._verifyNotCommitted();\n const t = __PRIVATE_validateReference(e, this._firestore);\n return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(t._key, Precondition.none())), \n this;\n }\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */ commit() {\n return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();\n }\n _verifyNotCommitted() {\n if (this._committed) throw new FirestoreError(D.FAILED_PRECONDITION, \"A write batch can no longer be used after commit() has been called.\");\n }\n}\n\nfunction __PRIVATE_validateReference(e, t) {\n if ((e = getModularInstance(e)).firestore !== t) throw new FirestoreError(D.INVALID_ARGUMENT, \"Provided document reference is from a different Firestore instance.\");\n return e;\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// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\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 * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nclass Transaction extends class Transaction$1 {\n /** @hideconstructor */\n constructor(e, t) {\n this._firestore = e, this._transaction = t, this._dataReader = __PRIVATE_newUserDataReader(e);\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(e) {\n const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ t._key ]).then((e => {\n if (!e || 1 !== e.length) return fail();\n const r = e[0];\n if (r.isFoundDocument()) return new DocumentSnapshot$1(this._firestore, n, r.key, r, t.converter);\n if (r.isNoDocument()) return new DocumentSnapshot$1(this._firestore, n, t._key, null, t.converter);\n throw fail();\n }));\n }\n set(e, t, n) {\n const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, \"Transaction.set\", r._key, i, null !== r.converter, n);\n return this._transaction.set(r._key, s), this;\n }\n update(e, t, n, ...r) {\n const i = __PRIVATE_validateReference(e, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let s;\n return s = \"string\" == typeof (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, \"Transaction.update\", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, \"Transaction.update\", i._key, t), \n this._transaction.update(i._key, s), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */ delete(e) {\n const t = __PRIVATE_validateReference(e, this._firestore);\n return this._transaction.delete(t._key), this;\n }\n} {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n /** @hideconstructor */\n constructor(e, t) {\n super(e, t), this._firestore = e;\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(e) {\n const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_ExpUserDataWriter(this._firestore);\n return super.get(e).then((e => new DocumentSnapshot(this._firestore, n, t._key, e._document, new SnapshotMetadata(\n /* hasPendingWrites= */ !1, \n /* fromCache= */ !1), t.converter)));\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */ function runTransaction(e, t, n) {\n e = __PRIVATE_cast(e, Firestore);\n const r = Object.assign(Object.assign({}, ve), n);\n !function __PRIVATE_validateTransactionOptions(e) {\n if (e.maxAttempts < 1) throw new FirestoreError(D.INVALID_ARGUMENT, \"Max attempts must be at least 1\");\n }(r);\n return function __PRIVATE_firestoreClientTransaction(e, t, n) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => {\n const i = await __PRIVATE_getDatastore(e);\n new __PRIVATE_TransactionRunner(e.asyncQueue, i, n, t, r).au();\n })), r.promise;\n }(ensureFirestoreConfigured(e), (n => t(new Transaction(e, n))), r);\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 * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */ function deleteField() {\n return new __PRIVATE_DeleteFieldValueImpl(\"deleteField\");\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */ function serverTimestamp() {\n return new __PRIVATE_ServerTimestampFieldValueImpl(\"serverTimestamp\");\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */ function arrayUnion(...e) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new __PRIVATE_ArrayUnionFieldValueImpl(\"arrayUnion\", e);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function arrayRemove(...e) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new __PRIVATE_ArrayRemoveFieldValueImpl(\"arrayRemove\", e);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function increment(e) {\n return new __PRIVATE_NumericIncrementFieldValueImpl(\"increment\", e);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */ function vector(e) {\n return new VectorValue(e);\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 * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */ function writeBatch(e) {\n return ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), new WriteBatch(e, (t => executeWrite(e, t)));\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function setIndexConfiguration(e, t) {\n const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore));\n if (!n._uninitializedComponentsProvider || \"memory\" === n._uninitializedComponentsProvider._offline.kind) \n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n return __PRIVATE_logWarn(\"Cannot enable indexes when persistence is disabled\"), \n Promise.resolve();\n const r = function __PRIVATE_parseIndexes(e) {\n const t = \"string\" == typeof e ? function __PRIVATE_tryParseJson(e) {\n try {\n return JSON.parse(e);\n } catch (e) {\n throw new FirestoreError(D.INVALID_ARGUMENT, \"Failed to parse JSON: \" + (null == e ? void 0 : e.message));\n }\n }(e) : e, n = [];\n if (Array.isArray(t.indexes)) for (const e of t.indexes) {\n const t = __PRIVATE_tryGetString(e, \"collectionGroup\"), r = [];\n if (Array.isArray(e.fields)) for (const t of e.fields) {\n const e = __PRIVATE_fieldPathFromDotSeparatedString(\"setIndexConfiguration\", __PRIVATE_tryGetString(t, \"fieldPath\"));\n \"CONTAINS\" === t.arrayConfig ? r.push(new IndexSegment(e, 2 /* IndexKind.CONTAINS */)) : \"ASCENDING\" === t.order ? r.push(new IndexSegment(e, 0 /* IndexKind.ASCENDING */)) : \"DESCENDING\" === t.order && r.push(new IndexSegment(e, 1 /* IndexKind.DESCENDING */));\n }\n n.push(new FieldIndex(FieldIndex.UNKNOWN_ID, t, r, IndexState.empty()));\n }\n return n;\n }(t);\n return __PRIVATE_firestoreClientSetIndexConfiguration(n, r);\n}\n\nfunction __PRIVATE_tryGetString(e, t) {\n if (\"string\" != typeof e[t]) throw new FirestoreError(D.INVALID_ARGUMENT, \"Missing string value for: \" + t);\n return e[t];\n}\n\n/**\n * @license\n * Copyright 2023 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 * A `PersistentCacheIndexManager` for configuring persistent cache indexes used\n * for local query execution.\n *\n * To use, call `getPersistentCacheIndexManager()` to get an instance.\n */ class PersistentCacheIndexManager {\n /** @hideconstructor */\n constructor(e) {\n this._firestore = e, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"PersistentCacheIndexManager\";\n }\n}\n\n/**\n * Returns the PersistentCache Index Manager used by the given `Firestore`\n * object.\n *\n * @return The `PersistentCacheIndexManager` instance, or `null` if local\n * persistent storage is not in use.\n */ function getPersistentCacheIndexManager(e) {\n var t;\n e = __PRIVATE_cast(e, Firestore);\n const n = Ce.get(e);\n if (n) return n;\n if (\"persistent\" !== (null === (t = ensureFirestoreConfigured(e)._uninitializedComponentsProvider) || void 0 === t ? void 0 : t._offline.kind)) return null;\n const r = new PersistentCacheIndexManager(e);\n return Ce.set(e, r), r;\n}\n\n/**\n * Enables the SDK to create persistent cache indexes automatically for local\n * query execution when the SDK believes cache indexes can help improve\n * performance.\n *\n * This feature is disabled by default.\n */ function enablePersistentCacheIndexAutoCreation(e) {\n __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !0);\n}\n\n/**\n * Stops creating persistent cache indexes automatically for local query\n * execution. The indexes which have been created by calling\n * `enablePersistentCacheIndexAutoCreation()` still take effect.\n */ function disablePersistentCacheIndexAutoCreation(e) {\n __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !1);\n}\n\n/**\n * Removes all persistent cache indexes.\n *\n * Please note this function will also deletes indexes generated by\n * `setIndexConfiguration()`, which is deprecated.\n */ function deleteAllPersistentCacheIndexes(e) {\n __PRIVATE_firestoreClientDeleteAllFieldIndexes(ensureFirestoreConfigured(e._firestore)).then((e => __PRIVATE_logDebug(\"deleting all persistent cache indexes succeeded\"))).catch((e => __PRIVATE_logWarn(\"deleting all persistent cache indexes failed\", e)));\n}\n\nfunction __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, t) {\n __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(ensureFirestoreConfigured(e._firestore), t).then((e => __PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e => __PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${t} failed`, e)));\n}\n\n/**\n * Maps `Firestore` instances to their corresponding\n * `PersistentCacheIndexManager` instances.\n *\n * Use a `WeakMap` so that the mapping will be automatically dropped when the\n * `Firestore` instance is garbage collected. This emulates a private member\n * as described in https://goo.gle/454yvug.\n */ const Ce = new WeakMap;\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `QueryTarget` representation of the given query. Returns `null`\n * if the Firestore client associated with the given query has not been\n * initialized or has been terminated.\n *\n * @param query - The Query to convert to proto representation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _internalQueryToProtoQueryTarget(e) {\n var t;\n const n = null === (t = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore))._onlineComponents) || void 0 === t ? void 0 : t.datastore.serializer;\n return void 0 === n ? null : __PRIVATE_toQueryTarget(n, __PRIVATE_queryToTarget(e._query))._t;\n}\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns `RunAggregationQueryRequest` which contains the proto representation\n * of the given aggregation query request. Returns null if the Firestore client\n * associated with the given query has not been initialized or has been\n * terminated.\n *\n * @param query - The Query to convert to proto representation.\n * @param aggregateSpec - The set of aggregations and their aliases.\n */ function _internalAggregationQueryToProtoRunAggregationQueryRequest(e, t) {\n var n;\n const r = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath))), i = null === (n = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore))._onlineComponents) || void 0 === n ? void 0 : n.datastore.serializer;\n return void 0 === i ? null : __PRIVATE_toRunAggregationQueryRequest(i, __PRIVATE_queryToAggregateTarget(e._query), r, \n /* skipAliasing= */ !0).request;\n}\n\n/**\n * @license\n * Copyright 2023 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 * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */ class TestingHooks {\n constructor() {\n throw new Error(\"instances of this class should not be created\");\n }\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */ static onExistenceFilterMismatch(e) {\n return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e);\n }\n}\n\n/**\n * The implementation of `TestingHooksSpi`.\n */ class __PRIVATE_TestingHooksSpiImpl {\n constructor() {\n this.Uu = new Map;\n }\n static get instance() {\n return Fe || (Fe = new __PRIVATE_TestingHooksSpiImpl, function __PRIVATE_setTestingHooksSpi(e) {\n if (Pe) throw new Error(\"a TestingHooksSpi instance is already set\");\n Pe = e;\n }(Fe)), Fe;\n }\n et(e) {\n this.Uu.forEach((t => t(e)));\n }\n onExistenceFilterMismatch(e) {\n const t = Symbol(), n = this.Uu;\n return n.set(t, e), () => n.delete(t);\n }\n}\n\nlet Fe = null;\n\n/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */ !function __PRIVATE_registerFirestore(e, t = !0) {\n !function __PRIVATE_setSDKVersion(e) {\n S = e;\n }(SDK_VERSION), _registerComponent(new Component(\"firestore\", ((e, {instanceIdentifier: n, options: r}) => {\n const i = e.getProvider(\"app\").getImmediate(), s = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e.getProvider(\"auth-internal\")), new __PRIVATE_FirebaseAppCheckTokenProvider(e.getProvider(\"app-check-internal\")), function __PRIVATE_databaseIdFromApp(e, t) {\n if (!Object.prototype.hasOwnProperty.apply(e.options, [ \"projectId\" ])) throw new FirestoreError(D.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n return new DatabaseId(e.options.projectId, t);\n }(i, n), i);\n return r = Object.assign({\n useFetchStreams: t\n }, r), s._setSettings(r), s;\n }), \"PUBLIC\").setMultipleInstances(!0)), registerVersion(w, \"4.7.3\", e), \n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(w, \"4.7.3\", \"esm2017\");\n}();\n\nexport { AbstractUserDataWriter, AggregateField, AggregateQuerySnapshot, Bytes, Se as CACHE_SIZE_UNLIMITED, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, LoadBundleTask, PersistentCacheIndexManager, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, SnapshotMetadata, Timestamp, Transaction, VectorValue, WriteBatch, __PRIVATE_AutoId as _AutoId, ByteString as _ByteString, DatabaseId as _DatabaseId, DocumentKey as _DocumentKey, __PRIVATE_EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider, __PRIVATE_EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider, FieldPath$1 as _FieldPath, TestingHooks as _TestingHooks, __PRIVATE_cast as _cast, __PRIVATE_debugAssert as _debugAssert, _internalAggregationQueryToProtoRunAggregationQueryRequest, _internalQueryToProtoQueryTarget, __PRIVATE_isBase64Available as _isBase64Available, __PRIVATE_logWarn as _logWarn, __PRIVATE_validateIsNotUsedTogether as _validateIsNotUsedTogether, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, count, deleteAllPersistentCacheIndexes, deleteDoc, deleteField, disableNetwork, disablePersistentCacheIndexAutoCreation, doc, documentId, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, enablePersistentCacheIndexAutoCreation, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getAggregateFromServer, getCountFromServer, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, getPersistentCacheIndexManager, increment, initializeFirestore, limit, limitToLast, loadBundle, memoryEagerGarbageCollector, memoryLocalCache, memoryLruGarbageCollector, namedQuery, onSnapshot, onSnapshotsInSync, or, orderBy, persistentLocalCache, persistentMultipleTabManager, persistentSingleTabManager, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setIndexConfiguration, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, waitForPendingWrites, where, writeBatch };\n//# sourceMappingURL=index.esm2017.js.map\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"10.14.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\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\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;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\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;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\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);\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); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\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\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\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\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","import { SDK_VERSION, _isFirebaseServerApp, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';\nimport { ErrorFactory, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, isCloudflareWorker, getModularInstance, base64Decode, getUA, isIE, createSubscribe, deepEqual, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';\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 TOTP: 'totp'\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 registered 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_CREDENTIAL */]: 'The supplied auth credential is incorrect, 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-password\" /* AuthErrorCode.MISSING_PASSWORD */]: 'A non-empty password must be provided',\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 [\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is missing when sending request to the backend.',\r\n [\"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is invalid when sending request to the backend.',\r\n [\"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */]: 'The reCAPTCHA action is invalid when sending request to the backend.',\r\n [\"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */]: 'reCAPTCHA Enterprise integration is not enabled for this project.',\r\n [\"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */]: 'The reCAPTCHA client type is missing when sending request to the backend.',\r\n [\"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is missing when sending request to the backend.',\r\n [\"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */]: 'Invalid request parameters.',\r\n [\"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is invalid when sending request to the backend.',\r\n [\"unsupported-password-policy-schema-version\" /* AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION */]: 'The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.',\r\n [\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: 'The password does not meet the requirements.'\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_LOGIN_CREDENTIALS: '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 RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\r\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\r\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\r\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\r\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\r\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\r\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\r\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\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 _logWarn(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.WARN) {\r\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\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 _serverAppCurrentUserOperationNotSupportedError(auth) {\r\n return _errorWithCustomMessage(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */, 'Operations that alter the current user are not supported in conjunction with FirebaseServerApp');\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\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 if (typeof globalThis !== 'undefined' && globalThis.fetch) {\r\n return globalThis.fetch;\r\n }\r\n if (typeof fetch !== 'undefined') {\r\n return 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 if (typeof globalThis !== 'undefined' && globalThis.Headers) {\r\n return globalThis.Headers;\r\n }\r\n if (typeof Headers !== 'undefined') {\r\n return 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 if (typeof globalThis !== 'undefined' && globalThis.Response) {\r\n return globalThis.Response;\r\n }\r\n if (typeof Response !== 'undefined') {\r\n return 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 */]: \"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */,\r\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\r\n // invalid.\r\n [\"INVALID_LOGIN_CREDENTIALS\" /* ServerError.INVALID_LOGIN_CREDENTIALS */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\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_CREDENTIAL */,\r\n [\"INVALID_PENDING_TOKEN\" /* ServerError.INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\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 [\"PASSWORD_DOES_NOT_MEET_REQUIREMENTS\" /* ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: \"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */,\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_CREDENTIAL */,\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 // Recaptcha related errors.\r\n [\"RECAPTCHA_NOT_ENABLED\" /* ServerError.RECAPTCHA_NOT_ENABLED */]: \"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,\r\n [\"MISSING_RECAPTCHA_TOKEN\" /* ServerError.MISSING_RECAPTCHA_TOKEN */]: \"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_TOKEN\" /* ServerError.INVALID_RECAPTCHA_TOKEN */]: \"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_ACTION\" /* ServerError.INVALID_RECAPTCHA_ACTION */]: \"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,\r\n [\"MISSING_CLIENT_TYPE\" /* ServerError.MISSING_CLIENT_TYPE */]: \"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */,\r\n [\"MISSING_RECAPTCHA_VERSION\" /* ServerError.MISSING_RECAPTCHA_VERSION */]: \"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,\r\n [\"INVALID_RECAPTCHA_VERSION\" /* ServerError.INVALID_RECAPTCHA_VERSION */]: \"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,\r\n [\"INVALID_REQ_TYPE\" /* ServerError.INVALID_REQ_TYPE */]: \"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */\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 const fetchArgs = Object.assign({ method,\r\n headers }, body);\r\n /* Security-conscious server-side frameworks tend to have built in mitigations for referrer\r\n problems\". See the Cloudflare GitHub issue #487: Error: The 'referrerPolicy' field on\r\n 'RequestInitializerDict' is not implemented.\"\r\n https://github.com/cloudflare/next-on-pages/issues/487 */\r\n if (!isCloudflareWorker()) {\r\n fetchArgs.referrerPolicy = 'no-referrer';\r\n }\r\n return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), fetchArgs);\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 // Changing this to a different error code will log user out when there is a network error\r\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\r\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\r\n _fail(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e) });\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\nfunction _parseEnforcementState(enforcementStateStr) {\r\n switch (enforcementStateStr) {\r\n case 'ENFORCE':\r\n return \"ENFORCE\" /* EnforcementState.ENFORCE */;\r\n case 'AUDIT':\r\n return \"AUDIT\" /* EnforcementState.AUDIT */;\r\n case 'OFF':\r\n return \"OFF\" /* EnforcementState.OFF */;\r\n default:\r\n return \"ENFORCEMENT_STATE_UNSPECIFIED\" /* EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED */;\r\n }\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\nfunction isV2(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.getResponse !== undefined);\r\n}\r\nfunction isEnterprise(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.enterprise !== undefined);\r\n}\r\nclass RecaptchaConfig {\r\n constructor(response) {\r\n /**\r\n * The reCAPTCHA site key.\r\n */\r\n this.siteKey = '';\r\n /**\r\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\r\n */\r\n this.recaptchaEnforcementState = [];\r\n if (response.recaptchaKey === undefined) {\r\n throw new Error('recaptchaKey undefined');\r\n }\r\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\r\n this.siteKey = response.recaptchaKey.split('/')[3];\r\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\r\n }\r\n /**\r\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\r\n *\r\n * @param providerStr - The provider whose enforcement state is to be returned.\r\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\r\n */\r\n getProviderEnforcementState(providerStr) {\r\n if (!this.recaptchaEnforcementState ||\r\n this.recaptchaEnforcementState.length === 0) {\r\n return null;\r\n }\r\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\r\n if (recaptchaEnforcementState.provider &&\r\n recaptchaEnforcementState.provider === providerStr) {\r\n return _parseEnforcementState(recaptchaEnforcementState.enforcementState);\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\r\n *\r\n * @param providerStr - The provider whose enablement state is to be returned.\r\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\r\n */\r\n isProviderEnabled(providerStr) {\r\n return (this.getProviderEnforcementState(providerStr) ===\r\n \"ENFORCE\" /* EnforcementState.ENFORCE */ ||\r\n this.getProviderEnforcementState(providerStr) === \"AUDIT\" /* EnforcementState.AUDIT */);\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 getRecaptchaParams(auth) {\r\n return ((await _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/recaptchaParams\" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\r\n}\r\nasync function getRecaptchaConfig(auth, request) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/recaptchaConfig\" /* Endpoint.GET_RECAPTCHA_CONFIG */, _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 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 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\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}\r\nasync function revokeToken(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts:revokeToken\" /* Endpoint.REVOKE_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 * 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 updateFromIdToken(idToken) {\r\n _assert(idToken.length !== 0, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = _tokenExpiresIn(idToken);\r\n this.updateTokensAndExpiration(idToken, null, expiresIn);\r\n }\r\n async getToken(auth, forceRefresh = false) {\r\n if (!forceRefresh && this.accessToken && !this.isExpired) {\r\n return this.accessToken;\r\n }\r\n _assert(this.refreshToken, auth, \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */);\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 const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));\r\n newUser.metadata._copy(this.metadata);\r\n return newUser;\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 if (_isFirebaseServerApp(this.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));\r\n }\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 /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromGetAccountInfoResponse(auth, response, idToken) {\r\n const coreAccount = response.users[0];\r\n _assert(coreAccount.localId !== undefined, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const providerData = coreAccount.providerUserInfo !== undefined\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const isAnonymous = !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromIdToken(idToken);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: coreAccount.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // update the user with data from the GetAccountInfo response.\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: !(coreAccount.email && coreAccount.passwordHash) &&\r\n !(providerData === null || providerData === void 0 ? void 0 : providerData.length)\r\n };\r\n Object.assign(user, updates);\r\n return user;\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 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}\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 2023 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 * Fetches the password policy for the currently set tenant or the project if no tenant is set.\r\n *\r\n * @param auth Auth object.\r\n * @param request Password policy request.\r\n * @returns Password policy response.\r\n */\r\nasync function _getPasswordPolicy(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/passwordPolicy\" /* Endpoint.GET_PASSWORD_POLICY */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 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// Minimum min password length enforced by the backend, even if no minimum length is set.\r\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\r\n/**\r\n * Stores password policy requirements and provides password validation against the policy.\r\n *\r\n * @internal\r\n */\r\nclass PasswordPolicyImpl {\r\n constructor(response) {\r\n var _a, _b, _c, _d;\r\n // Only include custom strength options defined in the response.\r\n const responseOptions = response.customStrengthOptions;\r\n this.customStrengthOptions = {};\r\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\r\n this.customStrengthOptions.minPasswordLength =\r\n (_a = responseOptions.minPasswordLength) !== null && _a !== void 0 ? _a : MINIMUM_MIN_PASSWORD_LENGTH;\r\n if (responseOptions.maxPasswordLength) {\r\n this.customStrengthOptions.maxPasswordLength =\r\n responseOptions.maxPasswordLength;\r\n }\r\n if (responseOptions.containsLowercaseCharacter !== undefined) {\r\n this.customStrengthOptions.containsLowercaseLetter =\r\n responseOptions.containsLowercaseCharacter;\r\n }\r\n if (responseOptions.containsUppercaseCharacter !== undefined) {\r\n this.customStrengthOptions.containsUppercaseLetter =\r\n responseOptions.containsUppercaseCharacter;\r\n }\r\n if (responseOptions.containsNumericCharacter !== undefined) {\r\n this.customStrengthOptions.containsNumericCharacter =\r\n responseOptions.containsNumericCharacter;\r\n }\r\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\r\n this.customStrengthOptions.containsNonAlphanumericCharacter =\r\n responseOptions.containsNonAlphanumericCharacter;\r\n }\r\n this.enforcementState = response.enforcementState;\r\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\r\n this.enforcementState = 'OFF';\r\n }\r\n // Use an empty string if no non-alphanumeric characters are specified in the response.\r\n this.allowedNonAlphanumericCharacters =\r\n (_c = (_b = response.allowedNonAlphanumericCharacters) === null || _b === void 0 ? void 0 : _b.join('')) !== null && _c !== void 0 ? _c : '';\r\n this.forceUpgradeOnSignin = (_d = response.forceUpgradeOnSignin) !== null && _d !== void 0 ? _d : false;\r\n this.schemaVersion = response.schemaVersion;\r\n }\r\n validatePassword(password) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const status = {\r\n isValid: true,\r\n passwordPolicy: this\r\n };\r\n // Check the password length and character options.\r\n this.validatePasswordLengthOptions(password, status);\r\n this.validatePasswordCharacterOptions(password, status);\r\n // Combine the status into single isValid property.\r\n status.isValid && (status.isValid = (_a = status.meetsMinPasswordLength) !== null && _a !== void 0 ? _a : true);\r\n status.isValid && (status.isValid = (_b = status.meetsMaxPasswordLength) !== null && _b !== void 0 ? _b : true);\r\n status.isValid && (status.isValid = (_c = status.containsLowercaseLetter) !== null && _c !== void 0 ? _c : true);\r\n status.isValid && (status.isValid = (_d = status.containsUppercaseLetter) !== null && _d !== void 0 ? _d : true);\r\n status.isValid && (status.isValid = (_e = status.containsNumericCharacter) !== null && _e !== void 0 ? _e : true);\r\n status.isValid && (status.isValid = (_f = status.containsNonAlphanumericCharacter) !== null && _f !== void 0 ? _f : true);\r\n return status;\r\n }\r\n /**\r\n * Validates that the password meets the length options for the policy.\r\n *\r\n * @param password Password to validate.\r\n * @param status Validation status.\r\n */\r\n validatePasswordLengthOptions(password, status) {\r\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\r\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\r\n if (minPasswordLength) {\r\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\r\n }\r\n if (maxPasswordLength) {\r\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\r\n }\r\n }\r\n /**\r\n * Validates that the password meets the character options for the policy.\r\n *\r\n * @param password Password to validate.\r\n * @param status Validation status.\r\n */\r\n validatePasswordCharacterOptions(password, status) {\r\n // Assign statuses for requirements even if the password is an empty string.\r\n this.updatePasswordCharacterOptionsStatuses(status, \r\n /* containsLowercaseCharacter= */ false, \r\n /* containsUppercaseCharacter= */ false, \r\n /* containsNumericCharacter= */ false, \r\n /* containsNonAlphanumericCharacter= */ false);\r\n let passwordChar;\r\n for (let i = 0; i < password.length; i++) {\r\n passwordChar = password.charAt(i);\r\n this.updatePasswordCharacterOptionsStatuses(status, \r\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\r\n passwordChar <= 'z', \r\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\r\n passwordChar <= 'Z', \r\n /* containsNumericCharacter= */ passwordChar >= '0' &&\r\n passwordChar <= '9', \r\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(passwordChar));\r\n }\r\n }\r\n /**\r\n * Updates the running validation status with the statuses for the character options.\r\n * Expected to be called each time a character is processed to update each option status\r\n * based on the current character.\r\n *\r\n * @param status Validation status.\r\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\r\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\r\n * @param containsNumericCharacter Whether the character is a numeric character.\r\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\r\n */\r\n updatePasswordCharacterOptionsStatuses(status, containsLowercaseCharacter, containsUppercaseCharacter, containsNumericCharacter, containsNonAlphanumericCharacter) {\r\n if (this.customStrengthOptions.containsLowercaseLetter) {\r\n status.containsLowercaseLetter || (status.containsLowercaseLetter = containsLowercaseCharacter);\r\n }\r\n if (this.customStrengthOptions.containsUppercaseLetter) {\r\n status.containsUppercaseLetter || (status.containsUppercaseLetter = containsUppercaseCharacter);\r\n }\r\n if (this.customStrengthOptions.containsNumericCharacter) {\r\n status.containsNumericCharacter || (status.containsNumericCharacter = containsNumericCharacter);\r\n }\r\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\r\n status.containsNonAlphanumericCharacter || (status.containsNonAlphanumericCharacter = containsNonAlphanumericCharacter);\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, appCheckServiceProvider, config) {\r\n this.app = app;\r\n this.heartbeatServiceProvider = heartbeatServiceProvider;\r\n this.appCheckServiceProvider = appCheckServiceProvider;\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 this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1;\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 this._agentRecaptchaConfig = null;\r\n this._tenantRecaptchaConfigs = {};\r\n this._projectPasswordPolicy = null;\r\n this._tenantPasswordPolicies = {};\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 initializeCurrentUserFromIdToken(idToken) {\r\n try {\r\n const response = await getAccountInfo(this, { idToken });\r\n const user = await UserImpl._fromGetAccountInfoResponse(this, response, idToken);\r\n await this.directlySetCurrentUser(user);\r\n }\r\n catch (err) {\r\n console.warn('FirebaseServerApp could not login user with provided authIdToken: ', err);\r\n await this.directlySetCurrentUser(null);\r\n }\r\n }\r\n async initializeCurrentUser(popupRedirectResolver) {\r\n var _a;\r\n if (_isFirebaseServerApp(this.app)) {\r\n const idToken = this.app.settings.authIdToken;\r\n if (idToken) {\r\n // Start the auth operation in the next tick to allow a moment for the customer's app to\r\n // attach an emulator, if desired.\r\n return new Promise(resolve => {\r\n setTimeout(() => this.initializeCurrentUserFromIdToken(idToken).then(resolve, resolve));\r\n });\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\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 // ┌> [] │\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 if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\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 if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\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 if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n return this.queue(async () => {\r\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\r\n });\r\n }\r\n _getRecaptchaConfig() {\r\n if (this.tenantId == null) {\r\n return this._agentRecaptchaConfig;\r\n }\r\n else {\r\n return this._tenantRecaptchaConfigs[this.tenantId];\r\n }\r\n }\r\n async validatePassword(password) {\r\n if (!this._getPasswordPolicyInternal()) {\r\n await this._updatePasswordPolicy();\r\n }\r\n // Password policy will be defined after fetching.\r\n const passwordPolicy = this._getPasswordPolicyInternal();\r\n // Check that the policy schema version is supported by the SDK.\r\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\r\n if (passwordPolicy.schemaVersion !==\r\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) {\r\n return Promise.reject(this._errorFactory.create(\"unsupported-password-policy-schema-version\" /* AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION */, {}));\r\n }\r\n return passwordPolicy.validatePassword(password);\r\n }\r\n _getPasswordPolicyInternal() {\r\n if (this.tenantId === null) {\r\n return this._projectPasswordPolicy;\r\n }\r\n else {\r\n return this._tenantPasswordPolicies[this.tenantId];\r\n }\r\n }\r\n async _updatePasswordPolicy() {\r\n const response = await _getPasswordPolicy(this);\r\n const passwordPolicy = new PasswordPolicyImpl(response);\r\n if (this.tenantId === null) {\r\n this._projectPasswordPolicy = passwordPolicy;\r\n }\r\n else {\r\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\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 authStateReady() {\r\n return new Promise((resolve, reject) => {\r\n if (this.currentUser) {\r\n resolve();\r\n }\r\n else {\r\n const unsubscribe = this.onAuthStateChanged(() => {\r\n unsubscribe();\r\n resolve();\r\n }, reject);\r\n }\r\n });\r\n }\r\n /**\r\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\r\n */\r\n async revokeAccessToken(token) {\r\n if (this.currentUser) {\r\n const idToken = await this.currentUser.getIdToken();\r\n // Generalize this to accept other providers once supported.\r\n const request = {\r\n providerId: 'apple.com',\r\n tokenType: \"ACCESS_TOKEN\" /* TokenType.ACCESS_TOKEN */,\r\n token,\r\n idToken\r\n };\r\n if (this.tenantId != null) {\r\n request.tenantId = this.tenantId;\r\n }\r\n await revokeToken(this, request);\r\n }\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 let isUnsubscribed = false;\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(() => {\r\n if (isUnsubscribed) {\r\n return;\r\n }\r\n cb(this.currentUser);\r\n });\r\n if (typeof nextOrObserver === 'function') {\r\n const unsubscribe = subscription.addObserver(nextOrObserver, error, completed);\r\n return () => {\r\n isUnsubscribed = true;\r\n unsubscribe();\r\n };\r\n }\r\n else {\r\n const unsubscribe = subscription.addObserver(nextOrObserver);\r\n return () => {\r\n isUnsubscribed = true;\r\n unsubscribe();\r\n };\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 // If the App Check service exists, add the App Check token in the headers\r\n const appCheckToken = await this._getAppCheckToken();\r\n if (appCheckToken) {\r\n headers[\"X-Firebase-AppCheck\" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;\r\n }\r\n return headers;\r\n }\r\n async _getAppCheckToken() {\r\n var _a;\r\n const appCheckTokenResult = await ((_a = this.appCheckServiceProvider\r\n .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken());\r\n if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {\r\n // Context: appCheck.getToken() will never throw even if an error happened.\r\n // In the error case, a dummy token will be returned along with an error field describing\r\n // the error. In general, we shouldn't care about the error condition and just use\r\n // the token (actual or dummy) to send requests.\r\n _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);\r\n }\r\n return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;\r\n }\r\n}\r\n/**\r\n * Method to be used to cast down to our private implementation 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 * @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\nlet externalJSProvider = {\r\n async loadJS() {\r\n throw new Error('Unable to load external scripts');\r\n },\r\n recaptchaV2Script: '',\r\n recaptchaEnterpriseScript: '',\r\n gapiScript: ''\r\n};\r\nfunction _setExternalJSProvider(p) {\r\n externalJSProvider = p;\r\n}\r\nfunction _loadJS(url) {\r\n return externalJSProvider.loadJS(url);\r\n}\r\nfunction _recaptchaV2ScriptUrl() {\r\n return externalJSProvider.recaptchaV2Script;\r\n}\r\nfunction _recaptchaEnterpriseScriptUrl() {\r\n return externalJSProvider.recaptchaEnterpriseScript;\r\n}\r\nfunction _gapiScriptUrl() {\r\n return externalJSProvider.gapiScript;\r\n}\r\nfunction _generateCallbackName(prefix) {\r\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\r\n}\n\n/* eslint-disable @typescript-eslint/no-require-imports */\r\nconst RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\r\nconst FAKE_TOKEN = 'NO_RECAPTCHA';\r\nclass RecaptchaEnterpriseVerifier {\r\n /**\r\n *\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n */\r\n constructor(authExtern) {\r\n /**\r\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\r\n */\r\n this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\r\n this.auth = _castAuth(authExtern);\r\n }\r\n /**\r\n * Executes the verification process.\r\n *\r\n * @returns A Promise for a token that can be used to assert the validity of a request.\r\n */\r\n async verify(action = 'verify', forceRefresh = false) {\r\n async function retrieveSiteKey(auth) {\r\n if (!forceRefresh) {\r\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\r\n return auth._agentRecaptchaConfig.siteKey;\r\n }\r\n if (auth.tenantId != null &&\r\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {\r\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\r\n }\r\n }\r\n return new Promise(async (resolve, reject) => {\r\n getRecaptchaConfig(auth, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n })\r\n .then(response => {\r\n if (response.recaptchaKey === undefined) {\r\n reject(new Error('recaptcha Enterprise site key undefined'));\r\n }\r\n else {\r\n const config = new RecaptchaConfig(response);\r\n if (auth.tenantId == null) {\r\n auth._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\r\n }\r\n return resolve(config.siteKey);\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n function retrieveRecaptchaToken(siteKey, resolve, reject) {\r\n const grecaptcha = window.grecaptcha;\r\n if (isEnterprise(grecaptcha)) {\r\n grecaptcha.enterprise.ready(() => {\r\n grecaptcha.enterprise\r\n .execute(siteKey, { action })\r\n .then(token => {\r\n resolve(token);\r\n })\r\n .catch(() => {\r\n resolve(FAKE_TOKEN);\r\n });\r\n });\r\n }\r\n else {\r\n reject(Error('No reCAPTCHA enterprise script loaded.'));\r\n }\r\n }\r\n return new Promise((resolve, reject) => {\r\n retrieveSiteKey(this.auth)\r\n .then(siteKey => {\r\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n }\r\n else {\r\n if (typeof window === 'undefined') {\r\n reject(new Error('RecaptchaVerifier is only supported in browser'));\r\n return;\r\n }\r\n let url = _recaptchaEnterpriseScriptUrl();\r\n if (url.length !== 0) {\r\n url += siteKey;\r\n }\r\n _loadJS(url)\r\n .then(() => {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n}\r\nasync function injectRecaptchaFields(auth, request, action, captchaResp = false) {\r\n const verifier = new RecaptchaEnterpriseVerifier(auth);\r\n let captchaResponse;\r\n try {\r\n captchaResponse = await verifier.verify(action);\r\n }\r\n catch (error) {\r\n captchaResponse = await verifier.verify(action, true);\r\n }\r\n const newRequest = Object.assign({}, request);\r\n if (!captchaResp) {\r\n Object.assign(newRequest, { captchaResponse });\r\n }\r\n else {\r\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\r\n }\r\n Object.assign(newRequest, { 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */ });\r\n Object.assign(newRequest, {\r\n 'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n return newRequest;\r\n}\r\nasync function handleRecaptchaFlow(authInstance, request, actionName, actionMethod) {\r\n var _a;\r\n if ((_a = authInstance\r\n ._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaProvider.EMAIL_PASSWORD_PROVIDER */)) {\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\r\n return actionMethod(authInstance, requestWithRecaptcha);\r\n }\r\n else {\r\n return actionMethod(authInstance, request).catch(async (error) => {\r\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n console.log(`${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\r\n return actionMethod(authInstance, requestWithRecaptcha);\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n}\r\nasync function _initializeRecaptchaConfig(auth) {\r\n const authInternal = _castAuth(auth);\r\n const response = await getRecaptchaConfig(authInternal, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n const config = new RecaptchaConfig(response);\r\n if (authInternal.tenantId == null) {\r\n authInternal._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\r\n }\r\n if (config.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaProvider.EMAIL_PASSWORD_PROVIDER */)) {\r\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\r\n void verifier.verify();\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 * 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 * 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\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\r\n// format as updateEmailPassword.\r\nasync function linkEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, 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 const request = {\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n return handleRecaptchaFlow(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */, signInWithPassword);\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 const request = {\r\n idToken,\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n return handleRecaptchaFlow(auth, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, linkEmailPassword);\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 {@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 * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\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 * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 * or a `TOKEN_EXPIRED` error.\r\n *\r\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\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 * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\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 else if ('totpInfo' in enrollment) {\r\n return TotpMultiFactorInfoImpl._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}\r\nclass TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"totp\" /* FactorId.TOTP */, response);\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new TotpMultiFactorInfoImpl(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 * Updates the password policy cached in the {@link Auth} instance if a policy is already\r\n * cached for the project or tenant.\r\n *\r\n * @remarks\r\n * We only fetch the password policy if the password did not meet policy requirements and\r\n * there is an existing policy cached. A developer must call validatePassword at least\r\n * once for the cache to be automatically updated.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @private\r\n */\r\nasync function recachePasswordPolicy(auth) {\r\n const authInternal = _castAuth(auth);\r\n if (authInternal._getPasswordPolicyInternal()) {\r\n await authInternal._updatePasswordPolicy();\r\n }\r\n}\r\n/**\r\n * Sends a password reset email to the given email address. This method does not throw an error when\r\n * there's no user account with the given email address and\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled.\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 authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendPasswordResetEmail$1);\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 .catch(async (error) => {\r\n if (error.code ===\r\n `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\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 * This method is not supported on {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n returnSecureToken: true,\r\n email,\r\n password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n const signUpResponse = handleRecaptchaFlow(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, signUp);\r\n const response = await signUpResponse.catch(error => {\r\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\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. When\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled, this method fails with \"auth/invalid-credential\" in case of an invalid\r\n * email/password.\r\n *\r\n * This method is not supported on {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 *\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password)).catch(async (error) => {\r\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\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 * 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 authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n function setActionCodeSettings(request, actionCodeSettings) {\r\n _assert(actionCodeSettings.handleCodeInApp, authInternal, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n }\r\n setActionCodeSettings(request, actionCodeSettings);\r\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendSignInLinkToEmail$1);\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 * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 *\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\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. This method returns an\r\n * empty list when\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled, irrespective of the number of authentication methods available for the given email.\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 * Deprecated. Migrating off of this method is recommended as a security best-practice.\r\n * Learn more in the Identity Platform documentation for\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}.\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 * This method is not supported on any {@link User} signed in by {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\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 * Throws \"auth/operation-not-allowed\" error when\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled.\r\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\r\n *\r\n * @public\r\n */\r\nfunction updateEmail(user, newEmail) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n return updateEmailOrPassword(userInternal, 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 * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 * Loads the reCAPTCHA configuration into the `Auth` instance.\r\n *\r\n * @remarks\r\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\r\n * verification flow should be triggered for each auth provider, into the\r\n * current Auth session.\r\n *\r\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\r\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\r\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\r\n * auth flows.\r\n *\r\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\r\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * initializeRecaptchaConfig(auth);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction initializeRecaptchaConfig(auth) {\r\n return _initializeRecaptchaConfig(auth);\r\n}\r\n/**\r\n * Validates the password against the password policy configured for the project or tenant.\r\n *\r\n * @remarks\r\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\r\n * policy configured for the project. Otherwise, this method will use the policy configured\r\n * for the tenant. If a password policy has not been configured, then the default policy\r\n * configured for all projects will be used.\r\n *\r\n * If an auth flow fails because a submitted password does not meet the password policy\r\n * requirements and this method has previously been called, then this method will use the\r\n * most recent policy available when called again.\r\n *\r\n * @example\r\n * ```javascript\r\n * validatePassword(auth, 'some-password');\r\n * ```\r\n *\r\n * @param auth The {@link Auth} instance.\r\n * @param password The password to validate.\r\n *\r\n * @public\r\n */\r\nasync function validatePassword(auth, password) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.validatePassword(password);\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 * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\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 * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 * @remarks\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 * Revokes the given access token. Currently only supports Apple OAuth access tokens.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param token - The Apple OAuth access token.\r\n *\r\n * @public\r\n */\r\nfunction revokeAccessToken(auth, token) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.revokeAccessToken(token);\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\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 MultiFactorSessionImpl {\r\n constructor(type, credential, user) {\r\n this.type = type;\r\n this.credential = credential;\r\n this.user = user;\r\n }\r\n static _fromIdtoken(idToken, user) {\r\n return new MultiFactorSessionImpl(\"enroll\" /* MultiFactorSessionType.ENROLL */, idToken, user);\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 startEnrollTotpMfa(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 finalizeEnrollTotpMfa(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);\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 try {\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 await this.user.reload();\r\n }\r\n catch (e) {\r\n throw e;\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\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 // 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 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 - Optional 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 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 if (result.length !== 0) {\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 }\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}\r\nfunction finalizeSignInTotpMfa(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\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\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) && isV2(_window().grecaptcha)) {\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 || !isV2(recaptcha)) {\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n return;\r\n }\r\n // Wrap the recaptcha 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 = `${_recaptchaV2ScriptUrl()}?${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 * @remarks\r\n * `RecaptchaVerifier` does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nclass RecaptchaVerifier {\r\n /**\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\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 constructor(authExtern, containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS)) {\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 * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\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 * @remarks\r\n * This method does not work in a Node.js environment.\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\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\r\n *\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\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 * @remarks\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\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 const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n await _link$1(userInternal, 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 * @remarks\r\n * `PhoneAuthProvider` does not work in a Node.js environment.\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 * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 * @public\r\n */\r\nasync function signInWithPopup(auth, provider, resolver) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_createError(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\r\n }\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 * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_createError(userInternal.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\r\n }\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 * This method does not work in a Node.js environment.\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. This is specifically true for\r\n // Firefox or if the opener is in an iframe, in which case the oauth\r\n // helper closes the popup.\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 }, 8000 /* _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 {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link signInWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\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 {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link reauthenticateWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\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 {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link linkWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\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 * @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 * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\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 if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\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 unloaded 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(`${_gapiScriptUrl()}?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\n/**\r\n * Fragment name for the App Check token that gets passed to the widget\r\n *\r\n * @internal\r\n */\r\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\r\nasync function _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 endpointId\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 // Sets the App Check token to pass to the widget\r\n const appCheckToken = await auth._getAppCheckToken();\r\n const appCheckTokenFragment = appCheckToken\r\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\r\n : '';\r\n // Start at index 1 to skip the leading '&' in the query string\r\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;\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 = await _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 const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n _setWindowLocation(url);\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 * @remarks\r\n * This method does not work in a Node.js environment.\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 * @remarks\r\n * This method does not work in a Node.js environment.\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\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass TotpMultiFactorGenerator {\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\r\n * the TOTP (time-based one-time password) second factor.\r\n * This assertion is used to complete enrollment in TOTP second factor.\r\n *\r\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorUser.enroll}.\r\n */\r\n static assertionForEnrollment(secret, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\r\n }\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\r\n * This assertion is used to complete signIn with TOTP as the second factor.\r\n *\r\n * @param enrollmentId identifies the enrolled TOTP second factor.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}.\r\n */\r\n static assertionForSignIn(enrollmentId, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);\r\n }\r\n /**\r\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\r\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\r\n * Used for generating a QR code URL or inputting into a TOTP app.\r\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\r\n *\r\n * @param session The {@link MultiFactorSession} that the user is part of.\r\n * @returns A promise to {@link TotpSecret}.\r\n */\r\n static async generateSecret(session) {\r\n var _a;\r\n const mfaSession = session;\r\n _assert(typeof ((_a = mfaSession.user) === null || _a === void 0 ? void 0 : _a.auth) !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollTotpMfa(mfaSession.user.auth, {\r\n idToken: mfaSession.credential,\r\n totpEnrollmentInfo: {}\r\n });\r\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.user.auth);\r\n }\r\n}\r\n/**\r\n * The identifier of the TOTP second factor: `totp`.\r\n */\r\nTotpMultiFactorGenerator.FACTOR_ID = \"totp\" /* FactorId.TOTP */;\r\nclass TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(otp, enrollmentId, secret) {\r\n super(\"totp\" /* FactorId.TOTP */);\r\n this.otp = otp;\r\n this.enrollmentId = enrollmentId;\r\n this.secret = secret;\r\n }\r\n /** @internal */\r\n static _fromSecret(secret, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\r\n }\r\n /** @internal */\r\n static _fromEnrollmentId(enrollmentId, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\r\n }\r\n /** @internal */\r\n async _finalizeEnroll(auth, idToken, displayName) {\r\n _assert(typeof this.secret !== 'undefined', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return finalizeEnrollTotpMfa(auth, {\r\n idToken,\r\n displayName,\r\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\r\n });\r\n }\r\n /** @internal */\r\n async _finalizeSignIn(auth, mfaPendingCredential) {\r\n _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n const totpVerificationInfo = { verificationCode: this.otp };\r\n return finalizeSignInTotpMfa(auth, {\r\n mfaPendingCredential,\r\n mfaEnrollmentId: this.enrollmentId,\r\n totpVerificationInfo\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * Stores the shared secret key and other parameters to generate time-based OTPs.\r\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\r\n * @public\r\n */\r\nclass TotpSecret {\r\n // The public members are declared outside the constructor so the docs can be generated.\r\n constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {\r\n this.sessionInfo = sessionInfo;\r\n this.auth = auth;\r\n this.secretKey = secretKey;\r\n this.hashingAlgorithm = hashingAlgorithm;\r\n this.codeLength = codeLength;\r\n this.codeIntervalSeconds = codeIntervalSeconds;\r\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\r\n }\r\n /** @internal */\r\n static _fromStartTotpMfaEnrollmentResponse(response, auth) {\r\n return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);\r\n }\r\n /** @internal */\r\n _makeTotpVerificationInfo(otp) {\r\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\r\n }\r\n /**\r\n * Returns a QR code URL as described in\r\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\r\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\r\n * If the optional parameters are unspecified, an accountName of and issuer of are used.\r\n *\r\n * @param accountName the name of the account/app along with a user identifier.\r\n * @param issuer issuer of the TOTP (likely the app name).\r\n * @returns A QR code URL string.\r\n */\r\n generateQrCodeUrl(accountName, issuer) {\r\n var _a;\r\n let useDefaults = false;\r\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\r\n useDefaults = true;\r\n }\r\n if (useDefaults) {\r\n if (_isEmptyString(accountName)) {\r\n accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';\r\n }\r\n if (_isEmptyString(issuer)) {\r\n issuer = this.auth.name;\r\n }\r\n }\r\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\r\n }\r\n}\r\n/** @internal */\r\nfunction _isEmptyString(input) {\r\n return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;\r\n}\n\nvar name = \"@firebase/auth\";\nvar version = \"1.7.9\";\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 case \"WebExtension\" /* ClientPlatform.WEB_EXTENSION */:\r\n return 'web-extension';\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 appCheckServiceProvider = container.getProvider('app-check-internal');\r\n const { apiKey, authDomain } = app.options;\r\n _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });\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, appCheckServiceProvider, config);\r\n _initializeAuthInstance(authInstance, deps);\r\n return authInstance;\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 authTokenSyncPath = getExperimentalSetting('authTokenSyncURL');\r\n // Only do the Cookie exchange in a secure context\r\n if (authTokenSyncPath &&\r\n typeof isSecureContext === 'boolean' &&\r\n isSecureContext) {\r\n // Don't allow urls (XSS possibility), only paths on the same domain\r\n const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);\r\n if (location.origin === authTokenSyncUrl.origin) {\r\n const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());\r\n beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));\r\n onIdTokenChanged(auth, user => mintCookie(user));\r\n }\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\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\n_setExternalJSProvider({\r\n 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\n gapiScript: 'https://apis.google.com/js/api.js',\r\n recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',\r\n recaptchaEnterpriseScript: 'https://www.google.com/recaptcha/enterprise.js?render='\r\n});\r\nregisterAuth(\"Browser\" /* ClientPlatform.BROWSER */);\n\nexport { TwitterAuthProvider as $, ActionCodeOperation as A, updateCurrentUser as B, signOut as C, revokeAccessToken as D, deleteUser as E, FactorId as F, debugErrorMap as G, prodErrorMap as H, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as I, initializeAuth as J, connectAuthEmulator as K, AuthCredential as L, EmailAuthCredential as M, OAuthCredential as N, OperationType as O, PhoneAuthProvider as P, PhoneAuthCredential as Q, RecaptchaVerifier as R, SignInMethod as S, TotpMultiFactorGenerator as T, inMemoryPersistence as U, EmailAuthProvider as V, FacebookAuthProvider as W, GoogleAuthProvider as X, GithubAuthProvider as Y, OAuthProvider as Z, SAMLAuthProvider as _, browserSessionPersistence as a, signInAnonymously as a0, signInWithCredential as a1, linkWithCredential as a2, reauthenticateWithCredential as a3, signInWithCustomToken as a4, sendPasswordResetEmail as a5, confirmPasswordReset as a6, applyActionCode as a7, checkActionCode as a8, verifyPasswordResetCode as a9, _isIOS7Or8 as aA, _createError as aB, _assert as aC, AuthEventManager as aD, _getInstance as aE, _persistenceKeyName as aF, _getRedirectResult as aG, _overrideRedirectResult as aH, _clearRedirectOutcomes as aI, _castAuth as aJ, UserImpl as aK, AuthImpl as aL, _getClientVersion as aM, _generateEventId as aN, AuthPopup as aO, FetchProvider as aP, SAMLAuthCredential as aQ, createUserWithEmailAndPassword as aa, signInWithEmailAndPassword as ab, sendSignInLinkToEmail as ac, isSignInWithEmailLink as ad, signInWithEmailLink as ae, fetchSignInMethodsForEmail as af, sendEmailVerification as ag, verifyBeforeUpdateEmail as ah, ActionCodeURL as ai, parseActionCodeURL as aj, updateProfile as ak, updateEmail as al, updatePassword as am, getIdToken as an, getIdTokenResult as ao, unlink as ap, getAdditionalUserInfo as aq, reload as ar, getMultiFactorResolver as as, multiFactor as at, debugAssert as au, _isIOS as av, _isAndroid as aw, _fail as ax, _getRedirectUrl as ay, _getProjectConfig 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, TotpSecret as n, getAuth as o, ProviderId as p, setPersistence as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, initializeRecaptchaConfig as t, updatePhoneNumber as u, validatePassword as v, onIdTokenChanged as w, beforeAuthStateChanged as x, onAuthStateChanged as y, useDeviceLanguage as z };\n//# sourceMappingURL=index-68602d24.js.map\n","import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component, ComponentContainer, Provider } from '@firebase/component';\nimport { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\n\nconst name = \"@firebase/database\";\nconst version = \"1.0.8\";\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/** The semver (www.semver.org) version of the SDK. */\r\nlet SDK_VERSION = '';\r\n/**\r\n * SDK_VERSION should be set before any database instance is created\r\n * @internal\r\n */\r\nfunction setSDKVersion(version) {\r\n SDK_VERSION = 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 * Wraps a DOM Storage object and:\r\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\r\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\r\n *\r\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\r\n * and one for localStorage.\r\n *\r\n */\r\nclass DOMStorageWrapper {\r\n /**\r\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\r\n */\r\n constructor(domStorage_) {\r\n this.domStorage_ = domStorage_;\r\n // Use a prefix to avoid collisions with other stuff saved by the app.\r\n this.prefix_ = 'firebase:';\r\n }\r\n /**\r\n * @param key - The key to save the value under\r\n * @param value - The value being stored, or null to remove the key.\r\n */\r\n set(key, value) {\r\n if (value == null) {\r\n this.domStorage_.removeItem(this.prefixedName_(key));\r\n }\r\n else {\r\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\r\n }\r\n }\r\n /**\r\n * @returns The value that was stored under this key, or null\r\n */\r\n get(key) {\r\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\r\n if (storedVal == null) {\r\n return null;\r\n }\r\n else {\r\n return jsonEval(storedVal);\r\n }\r\n }\r\n remove(key) {\r\n this.domStorage_.removeItem(this.prefixedName_(key));\r\n }\r\n prefixedName_(name) {\r\n return this.prefix_ + name;\r\n }\r\n toString() {\r\n return this.domStorage_.toString();\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/**\r\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\r\n * (TODO: create interface for both to implement).\r\n */\r\nclass MemoryStorage {\r\n constructor() {\r\n this.cache_ = {};\r\n this.isInMemoryStorage = true;\r\n }\r\n set(key, value) {\r\n if (value == null) {\r\n delete this.cache_[key];\r\n }\r\n else {\r\n this.cache_[key] = value;\r\n }\r\n }\r\n get(key) {\r\n if (contains(this.cache_, key)) {\r\n return this.cache_[key];\r\n }\r\n return null;\r\n }\r\n remove(key) {\r\n delete this.cache_[key];\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/**\r\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\r\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\r\n * to reflect this type\r\n *\r\n * @param domStorageName - Name of the underlying storage object\r\n * (e.g. 'localStorage' or 'sessionStorage').\r\n * @returns Turning off type information until a common interface is defined.\r\n */\r\nconst createStoragefor = function (domStorageName) {\r\n try {\r\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\r\n // so it must be inside the try/catch.\r\n if (typeof window !== 'undefined' &&\r\n typeof window[domStorageName] !== 'undefined') {\r\n // Need to test cache. Just because it's here doesn't mean it works\r\n const domStorage = window[domStorageName];\r\n domStorage.setItem('firebase:sentinel', 'cache');\r\n domStorage.removeItem('firebase:sentinel');\r\n return new DOMStorageWrapper(domStorage);\r\n }\r\n }\r\n catch (e) { }\r\n // Failed to create wrapper. Just return in-memory storage.\r\n // TODO: log?\r\n return new MemoryStorage();\r\n};\r\n/** A storage object that lasts across sessions */\r\nconst PersistentStorage = createStoragefor('localStorage');\r\n/** A storage object that only lasts one session */\r\nconst SessionStorage = createStoragefor('sessionStorage');\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 logClient = new Logger('@firebase/database');\r\n/**\r\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\r\n */\r\nconst LUIDGenerator = (function () {\r\n let id = 1;\r\n return function () {\r\n return id++;\r\n };\r\n})();\r\n/**\r\n * Sha1 hash of the input string\r\n * @param str - The string to hash\r\n * @returns {!string} The resulting hash\r\n */\r\nconst sha1 = function (str) {\r\n const utf8Bytes = stringToByteArray(str);\r\n const sha1 = new Sha1();\r\n sha1.update(utf8Bytes);\r\n const sha1Bytes = sha1.digest();\r\n return base64.encodeByteArray(sha1Bytes);\r\n};\r\nconst buildLogMessage_ = function (...varArgs) {\r\n let message = '';\r\n for (let i = 0; i < varArgs.length; i++) {\r\n const arg = varArgs[i];\r\n if (Array.isArray(arg) ||\r\n (arg &&\r\n typeof arg === 'object' &&\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n typeof arg.length === 'number')) {\r\n message += buildLogMessage_.apply(null, arg);\r\n }\r\n else if (typeof arg === 'object') {\r\n message += stringify(arg);\r\n }\r\n else {\r\n message += arg;\r\n }\r\n message += ' ';\r\n }\r\n return message;\r\n};\r\n/**\r\n * Use this for all debug messages in Firebase.\r\n */\r\nlet logger = null;\r\n/**\r\n * Flag to check for log availability on first log message\r\n */\r\nlet firstLog_ = true;\r\n/**\r\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\r\n * @param logger_ - A flag to turn on logging, or a custom logger\r\n * @param persistent - Whether or not to persist logging settings across refreshes\r\n */\r\nconst enableLogging$1 = function (logger_, persistent) {\r\n assert(!persistent || logger_ === true || logger_ === false, \"Can't turn on custom loggers persistently.\");\r\n if (logger_ === true) {\r\n logClient.logLevel = LogLevel.VERBOSE;\r\n logger = logClient.log.bind(logClient);\r\n if (persistent) {\r\n SessionStorage.set('logging_enabled', true);\r\n }\r\n }\r\n else if (typeof logger_ === 'function') {\r\n logger = logger_;\r\n }\r\n else {\r\n logger = null;\r\n SessionStorage.remove('logging_enabled');\r\n }\r\n};\r\nconst log = function (...varArgs) {\r\n if (firstLog_ === true) {\r\n firstLog_ = false;\r\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\r\n enableLogging$1(true);\r\n }\r\n }\r\n if (logger) {\r\n const message = buildLogMessage_.apply(null, varArgs);\r\n logger(message);\r\n }\r\n};\r\nconst logWrapper = function (prefix) {\r\n return function (...varArgs) {\r\n log(prefix, ...varArgs);\r\n };\r\n};\r\nconst error = function (...varArgs) {\r\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\r\n logClient.error(message);\r\n};\r\nconst fatal = function (...varArgs) {\r\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\r\n logClient.error(message);\r\n throw new Error(message);\r\n};\r\nconst warn = function (...varArgs) {\r\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\r\n logClient.warn(message);\r\n};\r\n/**\r\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\r\n * does not use https.\r\n */\r\nconst warnIfPageIsSecure = function () {\r\n // Be very careful accessing browser globals. Who knows what may or may not exist.\r\n if (typeof window !== 'undefined' &&\r\n window.location &&\r\n window.location.protocol &&\r\n window.location.protocol.indexOf('https:') !== -1) {\r\n warn('Insecure Firebase access from a secure page. ' +\r\n 'Please use https in calls to new Firebase().');\r\n }\r\n};\r\n/**\r\n * Returns true if data is NaN, or +/- Infinity.\r\n */\r\nconst isInvalidJSONNumber = function (data) {\r\n return (typeof data === 'number' &&\r\n (data !== data || // NaN\r\n data === Number.POSITIVE_INFINITY ||\r\n data === Number.NEGATIVE_INFINITY));\r\n};\r\nconst executeWhenDOMReady = function (fn) {\r\n if (isNodeSdk() || document.readyState === 'complete') {\r\n fn();\r\n }\r\n else {\r\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\r\n // fire before onload), but fall back to onload.\r\n let called = false;\r\n const wrappedFn = function () {\r\n if (!document.body) {\r\n setTimeout(wrappedFn, Math.floor(10));\r\n return;\r\n }\r\n if (!called) {\r\n called = true;\r\n fn();\r\n }\r\n };\r\n if (document.addEventListener) {\r\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\r\n // fallback to onload.\r\n window.addEventListener('load', wrappedFn, false);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (document.attachEvent) {\r\n // IE.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n document.attachEvent('onreadystatechange', () => {\r\n if (document.readyState === 'complete') {\r\n wrappedFn();\r\n }\r\n });\r\n // fallback to onload.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n window.attachEvent('onload', wrappedFn);\r\n // jQuery has an extra hack for IE that we could employ (based on\r\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\r\n // I'm hoping we don't need it.\r\n }\r\n }\r\n};\r\n/**\r\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\r\n */\r\nconst MIN_NAME = '[MIN_NAME]';\r\n/**\r\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\r\n */\r\nconst MAX_NAME = '[MAX_NAME]';\r\n/**\r\n * Compares valid Firebase key names, plus min and max name\r\n */\r\nconst nameCompare = function (a, b) {\r\n if (a === b) {\r\n return 0;\r\n }\r\n else if (a === MIN_NAME || b === MAX_NAME) {\r\n return -1;\r\n }\r\n else if (b === MIN_NAME || a === MAX_NAME) {\r\n return 1;\r\n }\r\n else {\r\n const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);\r\n if (aAsInt !== null) {\r\n if (bAsInt !== null) {\r\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (bAsInt !== null) {\r\n return 1;\r\n }\r\n else {\r\n return a < b ? -1 : 1;\r\n }\r\n }\r\n};\r\n/**\r\n * @returns {!number} comparison result.\r\n */\r\nconst stringCompare = function (a, b) {\r\n if (a === b) {\r\n return 0;\r\n }\r\n else if (a < b) {\r\n return -1;\r\n }\r\n else {\r\n return 1;\r\n }\r\n};\r\nconst requireKey = function (key, obj) {\r\n if (obj && key in obj) {\r\n return obj[key];\r\n }\r\n else {\r\n throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));\r\n }\r\n};\r\nconst ObjectToUniqueKey = function (obj) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return stringify(obj);\r\n }\r\n const keys = [];\r\n // eslint-disable-next-line guard-for-in\r\n for (const k in obj) {\r\n keys.push(k);\r\n }\r\n // Export as json, but with the keys sorted.\r\n keys.sort();\r\n let key = '{';\r\n for (let i = 0; i < keys.length; i++) {\r\n if (i !== 0) {\r\n key += ',';\r\n }\r\n key += stringify(keys[i]);\r\n key += ':';\r\n key += ObjectToUniqueKey(obj[keys[i]]);\r\n }\r\n key += '}';\r\n return key;\r\n};\r\n/**\r\n * Splits a string into a number of smaller segments of maximum size\r\n * @param str - The string\r\n * @param segsize - The maximum number of chars in the string.\r\n * @returns The string, split into appropriately-sized chunks\r\n */\r\nconst splitStringBySize = function (str, segsize) {\r\n const len = str.length;\r\n if (len <= segsize) {\r\n return [str];\r\n }\r\n const dataSegs = [];\r\n for (let c = 0; c < len; c += segsize) {\r\n if (c + segsize > len) {\r\n dataSegs.push(str.substring(c, len));\r\n }\r\n else {\r\n dataSegs.push(str.substring(c, c + segsize));\r\n }\r\n }\r\n return dataSegs;\r\n};\r\n/**\r\n * Apply a function to each (key, value) pair in an object or\r\n * apply a function to each (index, value) pair in an array\r\n * @param obj - The object or array to iterate over\r\n * @param fn - The function to apply\r\n */\r\nfunction each(obj, fn) {\r\n for (const key in obj) {\r\n if (obj.hasOwnProperty(key)) {\r\n fn(key, obj[key]);\r\n }\r\n }\r\n}\r\n/**\r\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\r\n * I made one modification at the end and removed the NaN / Infinity\r\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\r\n * @param v - A double\r\n *\r\n */\r\nconst doubleToIEEE754String = function (v) {\r\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\r\n const ebits = 11, fbits = 52;\r\n const bias = (1 << (ebits - 1)) - 1;\r\n let s, e, f, ln, i;\r\n // Compute sign, exponent, fraction\r\n // Skip NaN / Infinity handling --MJL.\r\n if (v === 0) {\r\n e = 0;\r\n f = 0;\r\n s = 1 / v === -Infinity ? 1 : 0;\r\n }\r\n else {\r\n s = v < 0;\r\n v = Math.abs(v);\r\n if (v >= Math.pow(2, 1 - bias)) {\r\n // Normalized\r\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\r\n e = ln + bias;\r\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\r\n }\r\n else {\r\n // Denormalized\r\n e = 0;\r\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\r\n }\r\n }\r\n // Pack sign, exponent, fraction\r\n const bits = [];\r\n for (i = fbits; i; i -= 1) {\r\n bits.push(f % 2 ? 1 : 0);\r\n f = Math.floor(f / 2);\r\n }\r\n for (i = ebits; i; i -= 1) {\r\n bits.push(e % 2 ? 1 : 0);\r\n e = Math.floor(e / 2);\r\n }\r\n bits.push(s ? 1 : 0);\r\n bits.reverse();\r\n const str = bits.join('');\r\n // Return the data as a hex string. --MJL\r\n let hexByteString = '';\r\n for (i = 0; i < 64; i += 8) {\r\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\r\n if (hexByte.length === 1) {\r\n hexByte = '0' + hexByte;\r\n }\r\n hexByteString = hexByteString + hexByte;\r\n }\r\n return hexByteString.toLowerCase();\r\n};\r\n/**\r\n * Used to detect if we're in a Chrome content script (which executes in an\r\n * isolated environment where long-polling doesn't work).\r\n */\r\nconst isChromeExtensionContentScript = function () {\r\n return !!(typeof window === 'object' &&\r\n window['chrome'] &&\r\n window['chrome']['extension'] &&\r\n !/^chrome/.test(window.location.href));\r\n};\r\n/**\r\n * Used to detect if we're in a Windows 8 Store app.\r\n */\r\nconst isWindowsStoreApp = function () {\r\n // Check for the presence of a couple WinRT globals\r\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\r\n};\r\n/**\r\n * Converts a server error code to a JavaScript Error\r\n */\r\nfunction errorForServerCode(code, query) {\r\n let reason = 'Unknown Error';\r\n if (code === 'too_big') {\r\n reason =\r\n 'The data requested exceeds the maximum size ' +\r\n 'that can be accessed with a single request.';\r\n }\r\n else if (code === 'permission_denied') {\r\n reason = \"Client doesn't have permission to access the desired data.\";\r\n }\r\n else if (code === 'unavailable') {\r\n reason = 'The service is unavailable';\r\n }\r\n const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n error.code = code.toUpperCase();\r\n return error;\r\n}\r\n/**\r\n * Used to test for integer-looking strings\r\n */\r\nconst INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\r\n/**\r\n * For use in keys, the minimum possible 32-bit integer.\r\n */\r\nconst INTEGER_32_MIN = -2147483648;\r\n/**\r\n * For use in keys, the maximum possible 32-bit integer.\r\n */\r\nconst INTEGER_32_MAX = 2147483647;\r\n/**\r\n * If the string contains a 32-bit integer, return it. Else return null.\r\n */\r\nconst tryParseInt = function (str) {\r\n if (INTEGER_REGEXP_.test(str)) {\r\n const intVal = Number(str);\r\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\r\n return intVal;\r\n }\r\n }\r\n return null;\r\n};\r\n/**\r\n * Helper to run some code but catch any exceptions and re-throw them later.\r\n * Useful for preventing user callbacks from breaking internal code.\r\n *\r\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\r\n * convenient (we don't have to try to figure out when is a safe point to\r\n * re-throw it), and the behavior seems reasonable:\r\n *\r\n * * If you aren't pausing on exceptions, you get an error in the console with\r\n * the correct stack trace.\r\n * * If you're pausing on all exceptions, the debugger will pause on your\r\n * exception and then again when we rethrow it.\r\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\r\n * on us re-throwing it.\r\n *\r\n * @param fn - The code to guard.\r\n */\r\nconst exceptionGuard = function (fn) {\r\n try {\r\n fn();\r\n }\r\n catch (e) {\r\n // Re-throw exception when it's safe.\r\n setTimeout(() => {\r\n // It used to be that \"throw e\" would result in a good console error with\r\n // relevant context, but as of Chrome 39, you just get the firebase.js\r\n // file/line number where we re-throw it, which is useless. So we log\r\n // e.stack explicitly.\r\n const stack = e.stack || '';\r\n warn('Exception was thrown by user callback.', stack);\r\n throw e;\r\n }, Math.floor(0));\r\n }\r\n};\r\n/**\r\n * @returns {boolean} true if we think we're currently being crawled.\r\n */\r\nconst beingCrawled = function () {\r\n const userAgent = (typeof window === 'object' &&\r\n window['navigator'] &&\r\n window['navigator']['userAgent']) ||\r\n '';\r\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\r\n // believe to support JavaScript/AJAX rendering.\r\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\r\n // would have seen the page\" is flaky if we don't treat it as a crawler.\r\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\r\n};\r\n/**\r\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\r\n *\r\n * It is removed with clearTimeout() as normal.\r\n *\r\n * @param fn - Function to run.\r\n * @param time - Milliseconds to wait before running.\r\n * @returns The setTimeout() return value.\r\n */\r\nconst setTimeoutNonBlocking = function (fn, time) {\r\n const timeout = setTimeout(fn, time);\r\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\r\n if (typeof timeout === 'number' &&\r\n // @ts-ignore Is only defined in Deno environments.\r\n typeof Deno !== 'undefined' &&\r\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\r\n Deno['unrefTimer']) {\r\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\r\n Deno.unrefTimer(timeout);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (typeof timeout === 'object' && timeout['unref']) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n timeout['unref']();\r\n }\r\n return timeout;\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 * Abstraction around AppCheck's token fetching capabilities.\r\n */\r\nclass AppCheckTokenProvider {\r\n constructor(appName_, appCheckProvider) {\r\n this.appName_ = appName_;\r\n this.appCheckProvider = appCheckProvider;\r\n this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });\r\n if (!this.appCheck) {\r\n appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));\r\n }\r\n }\r\n getToken(forceRefresh) {\r\n if (!this.appCheck) {\r\n return new Promise((resolve, reject) => {\r\n // Support delayed initialization of FirebaseAppCheck. This allows our\r\n // customers to initialize the RTDB SDK before initializing Firebase\r\n // AppCheck and ensures that all requests are authenticated if a token\r\n // becomes available before the timeout below expires.\r\n setTimeout(() => {\r\n if (this.appCheck) {\r\n this.getToken(forceRefresh).then(resolve, reject);\r\n }\r\n else {\r\n resolve(null);\r\n }\r\n }, 0);\r\n });\r\n }\r\n return this.appCheck.getToken(forceRefresh);\r\n }\r\n addTokenChangeListener(listener) {\r\n var _a;\r\n (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));\r\n }\r\n notifyForInvalidToken() {\r\n warn(`Provided AppCheck credentials for the app named \"${this.appName_}\" ` +\r\n 'are invalid. This usually indicates your app was not initialized correctly.');\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/**\r\n * Abstraction around FirebaseApp's token fetching capabilities.\r\n */\r\nclass FirebaseAuthTokenProvider {\r\n constructor(appName_, firebaseOptions_, authProvider_) {\r\n this.appName_ = appName_;\r\n this.firebaseOptions_ = firebaseOptions_;\r\n this.authProvider_ = authProvider_;\r\n this.auth_ = null;\r\n this.auth_ = authProvider_.getImmediate({ optional: true });\r\n if (!this.auth_) {\r\n authProvider_.onInit(auth => (this.auth_ = auth));\r\n }\r\n }\r\n getToken(forceRefresh) {\r\n if (!this.auth_) {\r\n return new Promise((resolve, reject) => {\r\n // Support delayed initialization of FirebaseAuth. This allows our\r\n // customers to initialize the RTDB SDK before initializing Firebase\r\n // Auth and ensures that all requests are authenticated if a token\r\n // becomes available before the timeout below expires.\r\n setTimeout(() => {\r\n if (this.auth_) {\r\n this.getToken(forceRefresh).then(resolve, reject);\r\n }\r\n else {\r\n resolve(null);\r\n }\r\n }, 0);\r\n });\r\n }\r\n return this.auth_.getToken(forceRefresh).catch(error => {\r\n // TODO: Need to figure out all the cases this is raised and whether\r\n // this makes sense.\r\n if (error && error.code === 'auth/token-not-initialized') {\r\n log('Got auth/token-not-initialized error. Treating as null token.');\r\n return null;\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n addTokenChangeListener(listener) {\r\n // TODO: We might want to wrap the listener and call it with no args to\r\n // avoid a leaky abstraction, but that makes removing the listener harder.\r\n if (this.auth_) {\r\n this.auth_.addAuthTokenListener(listener);\r\n }\r\n else {\r\n this.authProvider_\r\n .get()\r\n .then(auth => auth.addAuthTokenListener(listener));\r\n }\r\n }\r\n removeTokenChangeListener(listener) {\r\n this.authProvider_\r\n .get()\r\n .then(auth => auth.removeAuthTokenListener(listener));\r\n }\r\n notifyForInvalidToken() {\r\n let errorMessage = 'Provided authentication credentials for the app named \"' +\r\n this.appName_ +\r\n '\" are invalid. This usually indicates your app was not ' +\r\n 'initialized correctly. ';\r\n if ('credential' in this.firebaseOptions_) {\r\n errorMessage +=\r\n 'Make sure the \"credential\" property provided to initializeApp() ' +\r\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\r\n 'project.';\r\n }\r\n else if ('serviceAccount' in this.firebaseOptions_) {\r\n errorMessage +=\r\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\r\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\r\n 'project.';\r\n }\r\n else {\r\n errorMessage +=\r\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\r\n 'initializeApp() match the values provided for your app at ' +\r\n 'https://console.firebase.google.com/.';\r\n }\r\n warn(errorMessage);\r\n }\r\n}\r\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\r\nclass EmulatorTokenProvider {\r\n constructor(accessToken) {\r\n this.accessToken = accessToken;\r\n }\r\n getToken(forceRefresh) {\r\n return Promise.resolve({\r\n accessToken: this.accessToken\r\n });\r\n }\r\n addTokenChangeListener(listener) {\r\n // Invoke the listener immediately to match the behavior in Firebase Auth\r\n // (see packages/auth/src/auth.js#L1807)\r\n listener(this.accessToken);\r\n }\r\n removeTokenChangeListener(listener) { }\r\n notifyForInvalidToken() { }\r\n}\r\n/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\r\nEmulatorTokenProvider.OWNER = 'owner';\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 PROTOCOL_VERSION = '5';\r\nconst VERSION_PARAM = 'v';\r\nconst TRANSPORT_SESSION_PARAM = 's';\r\nconst REFERER_PARAM = 'r';\r\nconst FORGE_REF = 'f';\r\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\r\n// firebase.corp.google.com\r\nconst FORGE_DOMAIN_RE = /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\r\nconst LAST_SESSION_PARAM = 'ls';\r\nconst APPLICATION_ID_PARAM = 'p';\r\nconst APP_CHECK_TOKEN_PARAM = 'ac';\r\nconst WEBSOCKET = 'websocket';\r\nconst LONG_POLLING = 'long_polling';\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 * A class that holds metadata about a Repo object\r\n */\r\nclass RepoInfo {\r\n /**\r\n * @param host - Hostname portion of the url for the repo\r\n * @param secure - Whether or not this repo is accessed over ssl\r\n * @param namespace - The namespace represented by the repo\r\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\r\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\r\n * @param persistenceKey - Override the default session persistence storage key\r\n */\r\n constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {\r\n this.secure = secure;\r\n this.namespace = namespace;\r\n this.webSocketOnly = webSocketOnly;\r\n this.nodeAdmin = nodeAdmin;\r\n this.persistenceKey = persistenceKey;\r\n this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;\r\n this.isUsingEmulator = isUsingEmulator;\r\n this._host = host.toLowerCase();\r\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\r\n this.internalHost =\r\n PersistentStorage.get('host:' + host) || this._host;\r\n }\r\n isCacheableHost() {\r\n return this.internalHost.substr(0, 2) === 's-';\r\n }\r\n isCustomHost() {\r\n return (this._domain !== 'firebaseio.com' &&\r\n this._domain !== 'firebaseio-demo.com');\r\n }\r\n get host() {\r\n return this._host;\r\n }\r\n set host(newHost) {\r\n if (newHost !== this.internalHost) {\r\n this.internalHost = newHost;\r\n if (this.isCacheableHost()) {\r\n PersistentStorage.set('host:' + this._host, this.internalHost);\r\n }\r\n }\r\n }\r\n toString() {\r\n let str = this.toURLString();\r\n if (this.persistenceKey) {\r\n str += '<' + this.persistenceKey + '>';\r\n }\r\n return str;\r\n }\r\n toURLString() {\r\n const protocol = this.secure ? 'https://' : 'http://';\r\n const query = this.includeNamespaceInQueryParams\r\n ? `?ns=${this.namespace}`\r\n : '';\r\n return `${protocol}${this.host}/${query}`;\r\n }\r\n}\r\nfunction repoInfoNeedsQueryParam(repoInfo) {\r\n return (repoInfo.host !== repoInfo.internalHost ||\r\n repoInfo.isCustomHost() ||\r\n repoInfo.includeNamespaceInQueryParams);\r\n}\r\n/**\r\n * Returns the websocket URL for this repo\r\n * @param repoInfo - RepoInfo object\r\n * @param type - of connection\r\n * @param params - list\r\n * @returns The URL for this repo\r\n */\r\nfunction repoInfoConnectionURL(repoInfo, type, params) {\r\n assert(typeof type === 'string', 'typeof type must == string');\r\n assert(typeof params === 'object', 'typeof params must == object');\r\n let connURL;\r\n if (type === WEBSOCKET) {\r\n connURL =\r\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\r\n }\r\n else if (type === LONG_POLLING) {\r\n connURL =\r\n (repoInfo.secure ? 'https://' : 'http://') +\r\n repoInfo.internalHost +\r\n '/.lp?';\r\n }\r\n else {\r\n throw new Error('Unknown connection type: ' + type);\r\n }\r\n if (repoInfoNeedsQueryParam(repoInfo)) {\r\n params['ns'] = repoInfo.namespace;\r\n }\r\n const pairs = [];\r\n each(params, (key, value) => {\r\n pairs.push(key + '=' + value);\r\n });\r\n return connURL + pairs.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 * Tracks a collection of stats.\r\n */\r\nclass StatsCollection {\r\n constructor() {\r\n this.counters_ = {};\r\n }\r\n incrementCounter(name, amount = 1) {\r\n if (!contains(this.counters_, name)) {\r\n this.counters_[name] = 0;\r\n }\r\n this.counters_[name] += amount;\r\n }\r\n get() {\r\n return deepCopy(this.counters_);\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\nconst collections = {};\r\nconst reporters = {};\r\nfunction statsManagerGetCollection(repoInfo) {\r\n const hashString = repoInfo.toString();\r\n if (!collections[hashString]) {\r\n collections[hashString] = new StatsCollection();\r\n }\r\n return collections[hashString];\r\n}\r\nfunction statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {\r\n const hashString = repoInfo.toString();\r\n if (!reporters[hashString]) {\r\n reporters[hashString] = creatorFunction();\r\n }\r\n return reporters[hashString];\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 * This class ensures the packets from the server arrive in order\r\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\r\n */\r\nclass PacketReceiver {\r\n /**\r\n * @param onMessage_\r\n */\r\n constructor(onMessage_) {\r\n this.onMessage_ = onMessage_;\r\n this.pendingResponses = [];\r\n this.currentResponseNum = 0;\r\n this.closeAfterResponse = -1;\r\n this.onClose = null;\r\n }\r\n closeAfter(responseNum, callback) {\r\n this.closeAfterResponse = responseNum;\r\n this.onClose = callback;\r\n if (this.closeAfterResponse < this.currentResponseNum) {\r\n this.onClose();\r\n this.onClose = null;\r\n }\r\n }\r\n /**\r\n * Each message from the server comes with a response number, and an array of data. The responseNumber\r\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\r\n * browsers will respond in the same order as the requests we sent\r\n */\r\n handleResponse(requestNum, data) {\r\n this.pendingResponses[requestNum] = data;\r\n while (this.pendingResponses[this.currentResponseNum]) {\r\n const toProcess = this.pendingResponses[this.currentResponseNum];\r\n delete this.pendingResponses[this.currentResponseNum];\r\n for (let i = 0; i < toProcess.length; ++i) {\r\n if (toProcess[i]) {\r\n exceptionGuard(() => {\r\n this.onMessage_(toProcess[i]);\r\n });\r\n }\r\n }\r\n if (this.currentResponseNum === this.closeAfterResponse) {\r\n if (this.onClose) {\r\n this.onClose();\r\n this.onClose = null;\r\n }\r\n break;\r\n }\r\n this.currentResponseNum++;\r\n }\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// URL query parameters associated with longpolling\r\nconst FIREBASE_LONGPOLL_START_PARAM = 'start';\r\nconst FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\r\nconst FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\r\nconst FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\r\nconst FIREBASE_LONGPOLL_ID_PARAM = 'id';\r\nconst FIREBASE_LONGPOLL_PW_PARAM = 'pw';\r\nconst FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\r\nconst FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\r\nconst FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\r\nconst FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\r\nconst FIREBASE_LONGPOLL_DATA_PARAM = 'd';\r\nconst FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\r\n//Data size constants.\r\n//TODO: Perf: the maximum length actually differs from browser to browser.\r\n// We should check what browser we're on and set accordingly.\r\nconst MAX_URL_DATA_SIZE = 1870;\r\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\r\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\r\n/**\r\n * Keepalive period\r\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\r\n * length of 30 seconds that we can't exceed.\r\n */\r\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\r\n/**\r\n * How long to wait before aborting a long-polling connection attempt.\r\n */\r\nconst LP_CONNECT_TIMEOUT = 30000;\r\n/**\r\n * This class manages a single long-polling connection.\r\n */\r\nclass BrowserPollConnection {\r\n /**\r\n * @param connId An identifier for this connection, used for logging\r\n * @param repoInfo The info for the endpoint to send data to.\r\n * @param applicationId The Firebase App ID for this project.\r\n * @param appCheckToken The AppCheck token for this client.\r\n * @param authToken The AuthToken to use for this connection.\r\n * @param transportSessionId Optional transportSessionid if we are\r\n * reconnecting for an existing transport session\r\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\r\n * already created a connection previously\r\n */\r\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.repoInfo = repoInfo;\r\n this.applicationId = applicationId;\r\n this.appCheckToken = appCheckToken;\r\n this.authToken = authToken;\r\n this.transportSessionId = transportSessionId;\r\n this.lastSessionId = lastSessionId;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.everConnected_ = false;\r\n this.log_ = logWrapper(connId);\r\n this.stats_ = statsManagerGetCollection(repoInfo);\r\n this.urlFn = (params) => {\r\n // Always add the token if we have one.\r\n if (this.appCheckToken) {\r\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\r\n }\r\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\r\n };\r\n }\r\n /**\r\n * @param onMessage - Callback when messages arrive\r\n * @param onDisconnect - Callback with connection lost.\r\n */\r\n open(onMessage, onDisconnect) {\r\n this.curSegmentNum = 0;\r\n this.onDisconnect_ = onDisconnect;\r\n this.myPacketOrderer = new PacketReceiver(onMessage);\r\n this.isClosed_ = false;\r\n this.connectTimeoutTimer_ = setTimeout(() => {\r\n this.log_('Timed out trying to connect.');\r\n // Make sure we clear the host cache\r\n this.onClosed_();\r\n this.connectTimeoutTimer_ = null;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(LP_CONNECT_TIMEOUT));\r\n // Ensure we delay the creation of the iframe until the DOM is loaded.\r\n executeWhenDOMReady(() => {\r\n if (this.isClosed_) {\r\n return;\r\n }\r\n //Set up a callback that gets triggered once a connection is set up.\r\n this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {\r\n const [command, arg1, arg2, arg3, arg4] = args;\r\n this.incrementIncomingBytes_(args);\r\n if (!this.scriptTagHolder) {\r\n return; // we closed the connection.\r\n }\r\n if (this.connectTimeoutTimer_) {\r\n clearTimeout(this.connectTimeoutTimer_);\r\n this.connectTimeoutTimer_ = null;\r\n }\r\n this.everConnected_ = true;\r\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\r\n this.id = arg1;\r\n this.password = arg2;\r\n }\r\n else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\r\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\r\n if (arg1) {\r\n // We aren't expecting any more data (other than what the server's already in the process of sending us\r\n // through our already open polls), so don't send any more.\r\n this.scriptTagHolder.sendNewPolls = false;\r\n // arg1 in this case is the last response number sent by the server. We should try to receive\r\n // all of the responses up to this one before closing\r\n this.myPacketOrderer.closeAfter(arg1, () => {\r\n this.onClosed_();\r\n });\r\n }\r\n else {\r\n this.onClosed_();\r\n }\r\n }\r\n else {\r\n throw new Error('Unrecognized command received: ' + command);\r\n }\r\n }, (...args) => {\r\n const [pN, data] = args;\r\n this.incrementIncomingBytes_(args);\r\n this.myPacketOrderer.handleResponse(pN, data);\r\n }, () => {\r\n this.onClosed_();\r\n }, this.urlFn);\r\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\r\n //from cache.\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\r\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\r\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\r\n this.scriptTagHolder.uniqueCallbackIdentifier;\r\n }\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (this.transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\r\n }\r\n if (this.lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\r\n }\r\n if (this.applicationId) {\r\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\r\n }\r\n if (this.appCheckToken) {\r\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\r\n }\r\n if (typeof location !== 'undefined' &&\r\n location.hostname &&\r\n FORGE_DOMAIN_RE.test(location.hostname)) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n const connectURL = this.urlFn(urlParams);\r\n this.log_('Connecting via long-poll to ' + connectURL);\r\n this.scriptTagHolder.addTag(connectURL, () => {\r\n /* do nothing */\r\n });\r\n });\r\n }\r\n /**\r\n * Call this when a handshake has completed successfully and we want to consider the connection established\r\n */\r\n start() {\r\n this.scriptTagHolder.startLongPoll(this.id, this.password);\r\n this.addDisconnectPingFrame(this.id, this.password);\r\n }\r\n /**\r\n * Forces long polling to be considered as a potential transport\r\n */\r\n static forceAllow() {\r\n BrowserPollConnection.forceAllow_ = true;\r\n }\r\n /**\r\n * Forces longpolling to not be considered as a potential transport\r\n */\r\n static forceDisallow() {\r\n BrowserPollConnection.forceDisallow_ = true;\r\n }\r\n // Static method, use string literal so it can be accessed in a generic way\r\n static isAvailable() {\r\n if (isNodeSdk()) {\r\n return false;\r\n }\r\n else if (BrowserPollConnection.forceAllow_) {\r\n return true;\r\n }\r\n else {\r\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\r\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\r\n return (!BrowserPollConnection.forceDisallow_ &&\r\n typeof document !== 'undefined' &&\r\n document.createElement != null &&\r\n !isChromeExtensionContentScript() &&\r\n !isWindowsStoreApp());\r\n }\r\n }\r\n /**\r\n * No-op for polling\r\n */\r\n markConnectionHealthy() { }\r\n /**\r\n * Stops polling and cleans up the iframe\r\n */\r\n shutdown_() {\r\n this.isClosed_ = true;\r\n if (this.scriptTagHolder) {\r\n this.scriptTagHolder.close();\r\n this.scriptTagHolder = null;\r\n }\r\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\r\n if (this.myDisconnFrame) {\r\n document.body.removeChild(this.myDisconnFrame);\r\n this.myDisconnFrame = null;\r\n }\r\n if (this.connectTimeoutTimer_) {\r\n clearTimeout(this.connectTimeoutTimer_);\r\n this.connectTimeoutTimer_ = null;\r\n }\r\n }\r\n /**\r\n * Triggered when this transport is closed\r\n */\r\n onClosed_() {\r\n if (!this.isClosed_) {\r\n this.log_('Longpoll is closing itself');\r\n this.shutdown_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_(this.everConnected_);\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n }\r\n /**\r\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\r\n * that we've left.\r\n */\r\n close() {\r\n if (!this.isClosed_) {\r\n this.log_('Longpoll is being closed.');\r\n this.shutdown_();\r\n }\r\n }\r\n /**\r\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\r\n * broken into chunks (since URLs have a small maximum length).\r\n * @param data - The JSON data to transmit.\r\n */\r\n send(data) {\r\n const dataStr = stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //first, lets get the base64-encoded data\r\n const base64data = base64Encode(dataStr);\r\n //We can only fit a certain amount in each URL, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\r\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\r\n //of segments so that we can reassemble the packet on the server.\r\n for (let i = 0; i < dataSegs.length; i++) {\r\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\r\n this.curSegmentNum++;\r\n }\r\n }\r\n /**\r\n * This is how we notify the server that we're leaving.\r\n * We aren't able to send requests with DHTML on a window close event, but we can\r\n * trigger XHR requests in some browsers (everything but Opera basically).\r\n */\r\n addDisconnectPingFrame(id, pw) {\r\n if (isNodeSdk()) {\r\n return;\r\n }\r\n this.myDisconnFrame = document.createElement('iframe');\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\r\n this.myDisconnFrame.src = this.urlFn(urlParams);\r\n this.myDisconnFrame.style.display = 'none';\r\n document.body.appendChild(this.myDisconnFrame);\r\n }\r\n /**\r\n * Used to track the bytes received by this client\r\n */\r\n incrementIncomingBytes_(args) {\r\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\r\n const bytesReceived = stringify(args).length;\r\n this.bytesReceived += bytesReceived;\r\n this.stats_.incrementCounter('bytes_received', bytesReceived);\r\n }\r\n}\r\n/*********************************************************************************************\r\n * A wrapper around an iframe that is used as a long-polling script holder.\r\n *********************************************************************************************/\r\nclass FirebaseIFrameScriptHolder {\r\n /**\r\n * @param commandCB - The callback to be called when control commands are received from the server.\r\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\r\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\r\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\r\n */\r\n constructor(commandCB, onMessageCB, onDisconnect, urlFn) {\r\n this.onDisconnect = onDisconnect;\r\n this.urlFn = urlFn;\r\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\r\n //problems in some browsers.\r\n this.outstandingRequests = new Set();\r\n //A queue of the pending segments waiting for transmission to the server.\r\n this.pendingSegs = [];\r\n //A serial number. We use this for two things:\r\n // 1) A way to ensure the browser doesn't cache responses to polls\r\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\r\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\r\n // JSONP code in the order it was added to the iframe.\r\n this.currentSerial = Math.floor(Math.random() * 100000000);\r\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\r\n // incoming data from the server that we're waiting for).\r\n this.sendNewPolls = true;\r\n if (!isNodeSdk()) {\r\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\r\n //iframes where we put the long-polling script tags. We have two callbacks:\r\n // 1) Command Callback - Triggered for control issues, like starting a connection.\r\n // 2) Message Callback - Triggered when new data arrives.\r\n this.uniqueCallbackIdentifier = LUIDGenerator();\r\n window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\r\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\r\n onMessageCB;\r\n //Create an iframe for us to add script tags to.\r\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\r\n // Set the iframe's contents.\r\n let script = '';\r\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\r\n // for ie9, but ie8 needs to do it again in the document itself.\r\n if (this.myIFrame.src &&\r\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\r\n const currentDomain = document.domain;\r\n script = '';\r\n }\r\n const iframeContents = '' + script + '';\r\n try {\r\n this.myIFrame.doc.open();\r\n this.myIFrame.doc.write(iframeContents);\r\n this.myIFrame.doc.close();\r\n }\r\n catch (e) {\r\n log('frame writing exception');\r\n if (e.stack) {\r\n log(e.stack);\r\n }\r\n log(e);\r\n }\r\n }\r\n else {\r\n this.commandCB = commandCB;\r\n this.onMessageCB = onMessageCB;\r\n }\r\n }\r\n /**\r\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\r\n * actually use.\r\n */\r\n static createIFrame_() {\r\n const iframe = document.createElement('iframe');\r\n iframe.style.display = 'none';\r\n // This is necessary in order to initialize the document inside the iframe\r\n if (document.body) {\r\n document.body.appendChild(iframe);\r\n try {\r\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\r\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\r\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\r\n const a = iframe.contentWindow.document;\r\n if (!a) {\r\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\r\n log('No IE domain setting required');\r\n }\r\n }\r\n catch (e) {\r\n const domain = document.domain;\r\n iframe.src =\r\n \"javascript:void((function(){document.open();document.domain='\" +\r\n domain +\r\n \"';document.close();})())\";\r\n }\r\n }\r\n else {\r\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\r\n // never gets hit.\r\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\r\n }\r\n // Get the document of the iframe in a browser-specific way.\r\n if (iframe.contentDocument) {\r\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\r\n }\r\n else if (iframe.contentWindow) {\r\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (iframe.document) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n iframe.doc = iframe.document; //others?\r\n }\r\n return iframe;\r\n }\r\n /**\r\n * Cancel all outstanding queries and remove the frame.\r\n */\r\n close() {\r\n //Mark this iframe as dead, so no new requests are sent.\r\n this.alive = false;\r\n if (this.myIFrame) {\r\n //We have to actually remove all of the html inside this iframe before removing it from the\r\n //window, or IE will continue loading and executing the script tags we've already added, which\r\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\r\n this.myIFrame.doc.body.textContent = '';\r\n setTimeout(() => {\r\n if (this.myIFrame !== null) {\r\n document.body.removeChild(this.myIFrame);\r\n this.myIFrame = null;\r\n }\r\n }, Math.floor(0));\r\n }\r\n // Protect from being called recursively.\r\n const onDisconnect = this.onDisconnect;\r\n if (onDisconnect) {\r\n this.onDisconnect = null;\r\n onDisconnect();\r\n }\r\n }\r\n /**\r\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\r\n * @param id - The ID of this connection\r\n * @param pw - The password for this connection\r\n */\r\n startLongPoll(id, pw) {\r\n this.myID = id;\r\n this.myPW = pw;\r\n this.alive = true;\r\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\r\n while (this.newRequest_()) { }\r\n }\r\n /**\r\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\r\n * too many outstanding requests and we are still alive.\r\n *\r\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\r\n * needed.\r\n */\r\n newRequest_() {\r\n // We keep one outstanding request open all the time to receive data, but if we need to send data\r\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\r\n // close the old request.\r\n if (this.alive &&\r\n this.sendNewPolls &&\r\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {\r\n //construct our url\r\n this.currentSerial++;\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\r\n let theURL = this.urlFn(urlParams);\r\n //Now add as much data as we can.\r\n let curDataString = '';\r\n let i = 0;\r\n while (this.pendingSegs.length > 0) {\r\n //first, lets see if the next segment will fit.\r\n const nextSeg = this.pendingSegs[0];\r\n if (nextSeg.d.length +\r\n SEG_HEADER_SIZE +\r\n curDataString.length <=\r\n MAX_URL_DATA_SIZE) {\r\n //great, the segment will fit. Lets append it.\r\n const theSeg = this.pendingSegs.shift();\r\n curDataString =\r\n curDataString +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\r\n i +\r\n '=' +\r\n theSeg.seg +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\r\n i +\r\n '=' +\r\n theSeg.ts +\r\n '&' +\r\n FIREBASE_LONGPOLL_DATA_PARAM +\r\n i +\r\n '=' +\r\n theSeg.d;\r\n i++;\r\n }\r\n else {\r\n break;\r\n }\r\n }\r\n theURL = theURL + curDataString;\r\n this.addLongPollTag_(theURL, this.currentSerial);\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n /**\r\n * Queue a packet for transmission to the server.\r\n * @param segnum - A sequential id for this packet segment used for reassembly\r\n * @param totalsegs - The total number of segments in this packet\r\n * @param data - The data for this segment.\r\n */\r\n enqueueSegment(segnum, totalsegs, data) {\r\n //add this to the queue of segments to send.\r\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\r\n //send the data immediately if there isn't already data being transmitted, unless\r\n //startLongPoll hasn't been called yet.\r\n if (this.alive) {\r\n this.newRequest_();\r\n }\r\n }\r\n /**\r\n * Add a script tag for a regular long-poll request.\r\n * @param url - The URL of the script tag.\r\n * @param serial - The serial number of the request.\r\n */\r\n addLongPollTag_(url, serial) {\r\n //remember that we sent this request.\r\n this.outstandingRequests.add(serial);\r\n const doNewRequest = () => {\r\n this.outstandingRequests.delete(serial);\r\n this.newRequest_();\r\n };\r\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\r\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\r\n const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\r\n const readyStateCB = () => {\r\n // Request completed. Cancel the keepalive.\r\n clearTimeout(keepaliveTimeout);\r\n // Trigger a new request so we can continue receiving data.\r\n doNewRequest();\r\n };\r\n this.addTag(url, readyStateCB);\r\n }\r\n /**\r\n * Add an arbitrary script tag to the iframe.\r\n * @param url - The URL for the script tag source.\r\n * @param loadCB - A callback to be triggered once the script has loaded.\r\n */\r\n addTag(url, loadCB) {\r\n if (isNodeSdk()) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.doNodeLongPoll(url, loadCB);\r\n }\r\n else {\r\n setTimeout(() => {\r\n try {\r\n // if we're already closed, don't add this poll\r\n if (!this.sendNewPolls) {\r\n return;\r\n }\r\n const newScript = this.myIFrame.doc.createElement('script');\r\n newScript.type = 'text/javascript';\r\n newScript.async = true;\r\n newScript.src = url;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange =\r\n function () {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const rstate = newScript.readyState;\r\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange = null;\r\n if (newScript.parentNode) {\r\n newScript.parentNode.removeChild(newScript);\r\n }\r\n loadCB();\r\n }\r\n };\r\n newScript.onerror = () => {\r\n log('Long-poll script failed to load: ' + url);\r\n this.sendNewPolls = false;\r\n this.close();\r\n };\r\n this.myIFrame.doc.body.appendChild(newScript);\r\n }\r\n catch (e) {\r\n // TODO: we should make this error visible somehow\r\n }\r\n }, Math.floor(1));\r\n }\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\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\r\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\r\nlet WebSocketImpl = null;\r\nif (typeof MozWebSocket !== 'undefined') {\r\n WebSocketImpl = MozWebSocket;\r\n}\r\nelse if (typeof WebSocket !== 'undefined') {\r\n WebSocketImpl = WebSocket;\r\n}\r\n/**\r\n * Create a new websocket connection with the given callbacks.\r\n */\r\nclass WebSocketConnection {\r\n /**\r\n * @param connId identifier for this transport\r\n * @param repoInfo The info for the websocket endpoint.\r\n * @param applicationId The Firebase App ID for this project.\r\n * @param appCheckToken The App Check Token for this client.\r\n * @param authToken The Auth Token for this client.\r\n * @param transportSessionId Optional transportSessionId if this is connecting\r\n * to an existing transport session\r\n * @param lastSessionId Optional lastSessionId if there was a previous\r\n * connection\r\n */\r\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.applicationId = applicationId;\r\n this.appCheckToken = appCheckToken;\r\n this.authToken = authToken;\r\n this.keepaliveTimer = null;\r\n this.frames = null;\r\n this.totalFrames = 0;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.log_ = logWrapper(this.connId);\r\n this.stats_ = statsManagerGetCollection(repoInfo);\r\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);\r\n this.nodeAdmin = repoInfo.nodeAdmin;\r\n }\r\n /**\r\n * @param repoInfo - The info for the websocket endpoint.\r\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\r\n * @returns connection url\r\n */\r\n static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {\r\n const urlParams = {};\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (!isNodeSdk() &&\r\n typeof location !== 'undefined' &&\r\n location.hostname &&\r\n FORGE_DOMAIN_RE.test(location.hostname)) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n if (transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\r\n }\r\n if (lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\r\n }\r\n if (appCheckToken) {\r\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\r\n }\r\n if (applicationId) {\r\n urlParams[APPLICATION_ID_PARAM] = applicationId;\r\n }\r\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\r\n }\r\n /**\r\n * @param onMessage - Callback when messages arrive\r\n * @param onDisconnect - Callback with connection lost.\r\n */\r\n open(onMessage, onDisconnect) {\r\n this.onDisconnect = onDisconnect;\r\n this.onMessage = onMessage;\r\n this.log_('Websocket connecting to ' + this.connURL);\r\n this.everConnected_ = false;\r\n // Assume failure until proven otherwise.\r\n PersistentStorage.set('previous_websocket_failure', true);\r\n try {\r\n let options;\r\n if (isNodeSdk()) {\r\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\r\n // UA Format: Firebase////\r\n options = {\r\n headers: {\r\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\r\n 'X-Firebase-GMPID': this.applicationId || ''\r\n }\r\n };\r\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\r\n // Note that we send the credentials here even if they aren't admin credentials, which is\r\n // not a problem.\r\n // Note that this header is just used to bypass appcheck, and the token should still be sent\r\n // through the websocket connection once it is established.\r\n if (this.authToken) {\r\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\r\n }\r\n if (this.appCheckToken) {\r\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\r\n }\r\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\r\n const env = process['env'];\r\n const proxy = this.connURL.indexOf('wss://') === 0\r\n ? env['HTTPS_PROXY'] || env['https_proxy']\r\n : env['HTTP_PROXY'] || env['http_proxy'];\r\n if (proxy) {\r\n options['proxy'] = { origin: proxy };\r\n }\r\n }\r\n this.mySock = new WebSocketImpl(this.connURL, [], options);\r\n }\r\n catch (e) {\r\n this.log_('Error instantiating WebSocket.');\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n return;\r\n }\r\n this.mySock.onopen = () => {\r\n this.log_('Websocket connected.');\r\n this.everConnected_ = true;\r\n };\r\n this.mySock.onclose = () => {\r\n this.log_('Websocket connection was disconnected.');\r\n this.mySock = null;\r\n this.onClosed_();\r\n };\r\n this.mySock.onmessage = m => {\r\n this.handleIncomingFrame(m);\r\n };\r\n this.mySock.onerror = e => {\r\n this.log_('WebSocket error. Closing connection.');\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n };\r\n }\r\n /**\r\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\r\n */\r\n start() { }\r\n static forceDisallow() {\r\n WebSocketConnection.forceDisallow_ = true;\r\n }\r\n static isAvailable() {\r\n let isOldAndroid = false;\r\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\r\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\r\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\r\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\r\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\r\n isOldAndroid = true;\r\n }\r\n }\r\n }\r\n return (!isOldAndroid &&\r\n WebSocketImpl !== null &&\r\n !WebSocketConnection.forceDisallow_);\r\n }\r\n /**\r\n * Returns true if we previously failed to connect with this transport.\r\n */\r\n static previouslyFailed() {\r\n // If our persistent storage is actually only in-memory storage,\r\n // we default to assuming that it previously failed to be safe.\r\n return (PersistentStorage.isInMemoryStorage ||\r\n PersistentStorage.get('previous_websocket_failure') === true);\r\n }\r\n markConnectionHealthy() {\r\n PersistentStorage.remove('previous_websocket_failure');\r\n }\r\n appendFrame_(data) {\r\n this.frames.push(data);\r\n if (this.frames.length === this.totalFrames) {\r\n const fullMess = this.frames.join('');\r\n this.frames = null;\r\n const jsonMess = jsonEval(fullMess);\r\n //handle the message\r\n this.onMessage(jsonMess);\r\n }\r\n }\r\n /**\r\n * @param frameCount - The number of frames we are expecting from the server\r\n */\r\n handleNewFrameCount_(frameCount) {\r\n this.totalFrames = frameCount;\r\n this.frames = [];\r\n }\r\n /**\r\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\r\n * @returns Any remaining data to be process, or null if there is none\r\n */\r\n extractFrameCount_(data) {\r\n assert(this.frames === null, 'We already have a frame buffer');\r\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\r\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\r\n if (data.length <= 6) {\r\n const frameCount = Number(data);\r\n if (!isNaN(frameCount)) {\r\n this.handleNewFrameCount_(frameCount);\r\n return null;\r\n }\r\n }\r\n this.handleNewFrameCount_(1);\r\n return data;\r\n }\r\n /**\r\n * Process a websocket frame that has arrived from the server.\r\n * @param mess - The frame data\r\n */\r\n handleIncomingFrame(mess) {\r\n if (this.mySock === null) {\r\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\r\n }\r\n const data = mess['data'];\r\n this.bytesReceived += data.length;\r\n this.stats_.incrementCounter('bytes_received', data.length);\r\n this.resetKeepAlive();\r\n if (this.frames !== null) {\r\n // we're buffering\r\n this.appendFrame_(data);\r\n }\r\n else {\r\n // try to parse out a frame count, otherwise, assume 1 and process it\r\n const remainingData = this.extractFrameCount_(data);\r\n if (remainingData !== null) {\r\n this.appendFrame_(remainingData);\r\n }\r\n }\r\n }\r\n /**\r\n * Send a message to the server\r\n * @param data - The JSON object to transmit\r\n */\r\n send(data) {\r\n this.resetKeepAlive();\r\n const dataStr = stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //We can only fit a certain amount in each websocket frame, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\r\n //Send the length header\r\n if (dataSegs.length > 1) {\r\n this.sendString_(String(dataSegs.length));\r\n }\r\n //Send the actual data in segments.\r\n for (let i = 0; i < dataSegs.length; i++) {\r\n this.sendString_(dataSegs[i]);\r\n }\r\n }\r\n shutdown_() {\r\n this.isClosed_ = true;\r\n if (this.keepaliveTimer) {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = null;\r\n }\r\n if (this.mySock) {\r\n this.mySock.close();\r\n this.mySock = null;\r\n }\r\n }\r\n onClosed_() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is closing itself');\r\n this.shutdown_();\r\n // since this is an internal close, trigger the close listener\r\n if (this.onDisconnect) {\r\n this.onDisconnect(this.everConnected_);\r\n this.onDisconnect = null;\r\n }\r\n }\r\n }\r\n /**\r\n * External-facing close handler.\r\n * Close the websocket and kill the connection.\r\n */\r\n close() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is being closed');\r\n this.shutdown_();\r\n }\r\n }\r\n /**\r\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\r\n * the last activity.\r\n */\r\n resetKeepAlive() {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = setInterval(() => {\r\n //If there has been no websocket activity for a while, send a no-op\r\n if (this.mySock) {\r\n this.sendString_('0');\r\n }\r\n this.resetKeepAlive();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\r\n }\r\n /**\r\n * Send a string over the websocket.\r\n *\r\n * @param str - String to send.\r\n */\r\n sendString_(str) {\r\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\r\n // calls for some unknown reason. We treat these as an error and disconnect.\r\n // See https://app.asana.com/0/58926111402292/68021340250410\r\n try {\r\n this.mySock.send(str);\r\n }\r\n catch (e) {\r\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\r\n setTimeout(this.onClosed_.bind(this), 0);\r\n }\r\n }\r\n}\r\n/**\r\n * Number of response before we consider the connection \"healthy.\"\r\n */\r\nWebSocketConnection.responsesRequiredToBeHealthy = 2;\r\n/**\r\n * Time to wait for the connection te become healthy before giving up.\r\n */\r\nWebSocketConnection.healthyTimeout = 30000;\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 * Currently simplistic, this class manages what transport a Connection should use at various stages of its\r\n * lifecycle.\r\n *\r\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\r\n * they are available.\r\n */\r\nclass TransportManager {\r\n /**\r\n * @param repoInfo - Metadata around the namespace we're connecting to\r\n */\r\n constructor(repoInfo) {\r\n this.initTransports_(repoInfo);\r\n }\r\n static get ALL_TRANSPORTS() {\r\n return [BrowserPollConnection, WebSocketConnection];\r\n }\r\n /**\r\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\r\n * TransportManager has already set up transports_\r\n */\r\n static get IS_TRANSPORT_INITIALIZED() {\r\n return this.globalTransportInitialized_;\r\n }\r\n initTransports_(repoInfo) {\r\n const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\r\n let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\r\n if (repoInfo.webSocketOnly) {\r\n if (!isWebSocketsAvailable) {\r\n warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\r\n }\r\n isSkipPollConnection = true;\r\n }\r\n if (isSkipPollConnection) {\r\n this.transports_ = [WebSocketConnection];\r\n }\r\n else {\r\n const transports = (this.transports_ = []);\r\n for (const transport of TransportManager.ALL_TRANSPORTS) {\r\n if (transport && transport['isAvailable']()) {\r\n transports.push(transport);\r\n }\r\n }\r\n TransportManager.globalTransportInitialized_ = true;\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the initial transport to use\r\n */\r\n initialTransport() {\r\n if (this.transports_.length > 0) {\r\n return this.transports_[0];\r\n }\r\n else {\r\n throw new Error('No transports available');\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the next transport, or null\r\n */\r\n upgradeTransport() {\r\n if (this.transports_.length > 1) {\r\n return this.transports_[1];\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\r\n// Keeps track of whether the TransportManager has already chosen a transport to use\r\nTransportManager.globalTransportInitialized_ = false;\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// Abort upgrade attempt if it takes longer than 60s.\r\nconst UPGRADE_TIMEOUT = 60000;\r\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\r\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\r\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\r\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\r\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\r\n// but we've sent/received enough bytes, we don't cancel the connection.\r\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\r\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\r\nconst MESSAGE_TYPE = 't';\r\nconst MESSAGE_DATA = 'd';\r\nconst CONTROL_SHUTDOWN = 's';\r\nconst CONTROL_RESET = 'r';\r\nconst CONTROL_ERROR = 'e';\r\nconst CONTROL_PONG = 'o';\r\nconst SWITCH_ACK = 'a';\r\nconst END_TRANSMISSION = 'n';\r\nconst PING = 'p';\r\nconst SERVER_HELLO = 'h';\r\n/**\r\n * Creates a new real-time connection to the server using whichever method works\r\n * best in the current browser.\r\n */\r\nclass Connection {\r\n /**\r\n * @param id - an id for this connection\r\n * @param repoInfo_ - the info for the endpoint to connect to\r\n * @param applicationId_ - the Firebase App ID for this project\r\n * @param appCheckToken_ - The App Check Token for this device.\r\n * @param authToken_ - The auth token for this session.\r\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\r\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\r\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\r\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\r\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\r\n */\r\n constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\r\n this.id = id;\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.appCheckToken_ = appCheckToken_;\r\n this.authToken_ = authToken_;\r\n this.onMessage_ = onMessage_;\r\n this.onReady_ = onReady_;\r\n this.onDisconnect_ = onDisconnect_;\r\n this.onKill_ = onKill_;\r\n this.lastSessionId = lastSessionId;\r\n this.connectionCount = 0;\r\n this.pendingDataMessages = [];\r\n this.state_ = 0 /* RealtimeState.CONNECTING */;\r\n this.log_ = logWrapper('c:' + this.id + ':');\r\n this.transportManager_ = new TransportManager(repoInfo_);\r\n this.log_('Connection created');\r\n this.start_();\r\n }\r\n /**\r\n * Starts a connection attempt\r\n */\r\n start_() {\r\n const conn = this.transportManager_.initialTransport();\r\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessageReceived = this.connReceiver_(this.conn_);\r\n const onConnectionLost = this.disconnReceiver_(this.conn_);\r\n this.tx_ = this.conn_;\r\n this.rx_ = this.conn_;\r\n this.secondaryConn_ = null;\r\n this.isHealthy_ = false;\r\n /*\r\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\r\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\r\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\r\n * still have the context of your originating frame.\r\n */\r\n setTimeout(() => {\r\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\r\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\r\n }, Math.floor(0));\r\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\r\n if (healthyTimeoutMS > 0) {\r\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\r\n this.healthyTimeout_ = null;\r\n if (!this.isHealthy_) {\r\n if (this.conn_ &&\r\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has received ' +\r\n this.conn_.bytesReceived +\r\n ' bytes. Marking connection healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n else if (this.conn_ &&\r\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has sent ' +\r\n this.conn_.bytesSent +\r\n ' bytes. Leaving connection alive.');\r\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\r\n // the server.\r\n }\r\n else {\r\n this.log_('Closing unhealthy connection after timeout.');\r\n this.close();\r\n }\r\n }\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(healthyTimeoutMS));\r\n }\r\n }\r\n nextTransportId_() {\r\n return 'c:' + this.id + ':' + this.connectionCount++;\r\n }\r\n disconnReceiver_(conn) {\r\n return everConnected => {\r\n if (conn === this.conn_) {\r\n this.onConnectionLost_(everConnected);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.log_('Secondary connection lost.');\r\n this.onSecondaryConnectionLost_();\r\n }\r\n else {\r\n this.log_('closing an old connection');\r\n }\r\n };\r\n }\r\n connReceiver_(conn) {\r\n return (message) => {\r\n if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\r\n if (conn === this.rx_) {\r\n this.onPrimaryMessageReceived_(message);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.onSecondaryMessageReceived_(message);\r\n }\r\n else {\r\n this.log_('message on old connection');\r\n }\r\n }\r\n };\r\n }\r\n /**\r\n * @param dataMsg - An arbitrary data message to be sent to the server\r\n */\r\n sendRequest(dataMsg) {\r\n // wrap in a data message envelope and send it on\r\n const msg = { t: 'd', d: dataMsg };\r\n this.sendData_(msg);\r\n }\r\n tryCleanupConnection() {\r\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\r\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\r\n this.conn_ = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n // the server will shutdown the old connection\r\n }\r\n }\r\n onSecondaryControl_(controlData) {\r\n if (MESSAGE_TYPE in controlData) {\r\n const cmd = controlData[MESSAGE_TYPE];\r\n if (cmd === SWITCH_ACK) {\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // Most likely the session wasn't valid. Abandon the switch attempt\r\n this.log_('Got a reset on secondary, closing it');\r\n this.secondaryConn_.close();\r\n // If we were already using this connection for something, than we need to fully close\r\n if (this.tx_ === this.secondaryConn_ ||\r\n this.rx_ === this.secondaryConn_) {\r\n this.close();\r\n }\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on secondary.');\r\n this.secondaryResponsesRequired_--;\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n }\r\n }\r\n onSecondaryMessageReceived_(parsedData) {\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onSecondaryControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n // got a data message, but we're still second connection. Need to buffer it up\r\n this.pendingDataMessages.push(data);\r\n }\r\n else {\r\n throw new Error('Unknown protocol layer: ' + layer);\r\n }\r\n }\r\n upgradeIfSecondaryHealthy_() {\r\n if (this.secondaryResponsesRequired_ <= 0) {\r\n this.log_('Secondary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.secondaryConn_.markConnectionHealthy();\r\n this.proceedWithUpgrade_();\r\n }\r\n else {\r\n // Send a ping to make sure the connection is healthy.\r\n this.log_('sending ping on secondary.');\r\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n proceedWithUpgrade_() {\r\n // tell this connection to consider itself open\r\n this.secondaryConn_.start();\r\n // send ack\r\n this.log_('sending client ack on secondary');\r\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\r\n // send end packet on primary transport, switch to sending on this one\r\n // can receive on this one, buffer responses until end received on primary transport\r\n this.log_('Ending transmission on primary');\r\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\r\n this.tx_ = this.secondaryConn_;\r\n this.tryCleanupConnection();\r\n }\r\n onPrimaryMessageReceived_(parsedData) {\r\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n this.onDataMessage_(data);\r\n }\r\n }\r\n onDataMessage_(message) {\r\n this.onPrimaryResponse_();\r\n // We don't do anything with data messages, just kick them up a level\r\n this.onMessage_(message);\r\n }\r\n onPrimaryResponse_() {\r\n if (!this.isHealthy_) {\r\n this.primaryResponsesRequired_--;\r\n if (this.primaryResponsesRequired_ <= 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n }\r\n }\r\n onControl_(controlData) {\r\n const cmd = requireKey(MESSAGE_TYPE, controlData);\r\n if (MESSAGE_DATA in controlData) {\r\n const payload = controlData[MESSAGE_DATA];\r\n if (cmd === SERVER_HELLO) {\r\n const handshakePayload = Object.assign({}, payload);\r\n if (this.repoInfo_.isUsingEmulator) {\r\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\r\n handshakePayload.h = this.repoInfo_.host;\r\n }\r\n this.onHandshake_(handshakePayload);\r\n }\r\n else if (cmd === END_TRANSMISSION) {\r\n this.log_('recvd end transmission on primary');\r\n this.rx_ = this.secondaryConn_;\r\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\r\n this.onDataMessage_(this.pendingDataMessages[i]);\r\n }\r\n this.pendingDataMessages = [];\r\n this.tryCleanupConnection();\r\n }\r\n else if (cmd === CONTROL_SHUTDOWN) {\r\n // This was previously the 'onKill' callback passed to the lower-level connection\r\n // payload in this case is the reason for the shutdown. Generally a human-readable error\r\n this.onConnectionShutdown_(payload);\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // payload in this case is the host we should contact\r\n this.onReset_(payload);\r\n }\r\n else if (cmd === CONTROL_ERROR) {\r\n error('Server Error: ' + payload);\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on primary.');\r\n this.onPrimaryResponse_();\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }\r\n else {\r\n error('Unknown control packet command: ' + cmd);\r\n }\r\n }\r\n }\r\n /**\r\n * @param handshake - The handshake data returned from the server\r\n */\r\n onHandshake_(handshake) {\r\n const timestamp = handshake.ts;\r\n const version = handshake.v;\r\n const host = handshake.h;\r\n this.sessionId = handshake.s;\r\n this.repoInfo_.host = host;\r\n // if we've already closed the connection, then don't bother trying to progress further\r\n if (this.state_ === 0 /* RealtimeState.CONNECTING */) {\r\n this.conn_.start();\r\n this.onConnectionEstablished_(this.conn_, timestamp);\r\n if (PROTOCOL_VERSION !== version) {\r\n warn('Protocol version mismatch detected');\r\n }\r\n // TODO: do we want to upgrade? when? maybe a delay?\r\n this.tryStartUpgrade_();\r\n }\r\n }\r\n tryStartUpgrade_() {\r\n const conn = this.transportManager_.upgradeTransport();\r\n if (conn) {\r\n this.startUpgrade_(conn);\r\n }\r\n }\r\n startUpgrade_(conn) {\r\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.secondaryResponsesRequired_ =\r\n conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessage = this.connReceiver_(this.secondaryConn_);\r\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\r\n this.secondaryConn_.open(onMessage, onDisconnect);\r\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\r\n setTimeoutNonBlocking(() => {\r\n if (this.secondaryConn_) {\r\n this.log_('Timed out trying to upgrade.');\r\n this.secondaryConn_.close();\r\n }\r\n }, Math.floor(UPGRADE_TIMEOUT));\r\n }\r\n onReset_(host) {\r\n this.log_('Reset packet received. New host: ' + host);\r\n this.repoInfo_.host = host;\r\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\r\n // We don't currently support resets after the connection has already been established\r\n if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.close();\r\n }\r\n else {\r\n // Close whatever connections we have open and start again.\r\n this.closeConnections_();\r\n this.start_();\r\n }\r\n }\r\n onConnectionEstablished_(conn, timestamp) {\r\n this.log_('Realtime connection established.');\r\n this.conn_ = conn;\r\n this.state_ = 1 /* RealtimeState.CONNECTED */;\r\n if (this.onReady_) {\r\n this.onReady_(timestamp, this.sessionId);\r\n this.onReady_ = null;\r\n }\r\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\r\n // send some pings.\r\n if (this.primaryResponsesRequired_ === 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n }\r\n else {\r\n setTimeoutNonBlocking(() => {\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\r\n }\r\n }\r\n sendPingOnPrimaryIfNecessary_() {\r\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\r\n if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.log_('sending ping on primary.');\r\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n onSecondaryConnectionLost_() {\r\n const conn = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n if (this.tx_ === conn || this.rx_ === conn) {\r\n // we are relying on this connection already in some capacity. Therefore, a failure is real\r\n this.close();\r\n }\r\n }\r\n /**\r\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\r\n * we should flush the host cache\r\n */\r\n onConnectionLost_(everConnected) {\r\n this.conn_ = null;\r\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\r\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\r\n if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {\r\n this.log_('Realtime connection failed.');\r\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\r\n if (this.repoInfo_.isCacheableHost()) {\r\n PersistentStorage.remove('host:' + this.repoInfo_.host);\r\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\r\n this.repoInfo_.internalHost = this.repoInfo_.host;\r\n }\r\n }\r\n else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.log_('Realtime connection lost.');\r\n }\r\n this.close();\r\n }\r\n onConnectionShutdown_(reason) {\r\n this.log_('Connection shutdown command received. Shutting down...');\r\n if (this.onKill_) {\r\n this.onKill_(reason);\r\n this.onKill_ = null;\r\n }\r\n // We intentionally don't want to fire onDisconnect (kill is a different case),\r\n // so clear the callback.\r\n this.onDisconnect_ = null;\r\n this.close();\r\n }\r\n sendData_(data) {\r\n if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {\r\n throw 'Connection is not connected';\r\n }\r\n else {\r\n this.tx_.send(data);\r\n }\r\n }\r\n /**\r\n * Cleans up this connection, calling the appropriate callbacks\r\n */\r\n close() {\r\n if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\r\n this.log_('Closing realtime connection.');\r\n this.state_ = 2 /* RealtimeState.DISCONNECTED */;\r\n this.closeConnections_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_();\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n }\r\n closeConnections_() {\r\n this.log_('Shutting down all connections');\r\n if (this.conn_) {\r\n this.conn_.close();\r\n this.conn_ = null;\r\n }\r\n if (this.secondaryConn_) {\r\n this.secondaryConn_.close();\r\n this.secondaryConn_ = null;\r\n }\r\n if (this.healthyTimeout_) {\r\n clearTimeout(this.healthyTimeout_);\r\n this.healthyTimeout_ = null;\r\n }\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/**\r\n * Interface defining the set of actions that can be performed against the Firebase server\r\n * (basically corresponds to our wire protocol).\r\n *\r\n * @interface\r\n */\r\nclass ServerActions {\r\n put(pathString, data, onComplete, hash) { }\r\n merge(pathString, data, onComplete, hash) { }\r\n /**\r\n * Refreshes the auth token for the current connection.\r\n * @param token - The authentication token\r\n */\r\n refreshAuthToken(token) { }\r\n /**\r\n * Refreshes the app check token for the current connection.\r\n * @param token The app check token\r\n */\r\n refreshAppCheckToken(token) { }\r\n onDisconnectPut(pathString, data, onComplete) { }\r\n onDisconnectMerge(pathString, data, onComplete) { }\r\n onDisconnectCancel(pathString, onComplete) { }\r\n reportStats(stats) { }\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 * Base class to be used if you want to emit events. Call the constructor with\r\n * the set of allowed event names.\r\n */\r\nclass EventEmitter {\r\n constructor(allowedEvents_) {\r\n this.allowedEvents_ = allowedEvents_;\r\n this.listeners_ = {};\r\n assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\r\n }\r\n /**\r\n * To be called by derived classes to trigger events.\r\n */\r\n trigger(eventType, ...varArgs) {\r\n if (Array.isArray(this.listeners_[eventType])) {\r\n // Clone the list, since callbacks could add/remove listeners.\r\n const listeners = [...this.listeners_[eventType]];\r\n for (let i = 0; i < listeners.length; i++) {\r\n listeners[i].callback.apply(listeners[i].context, varArgs);\r\n }\r\n }\r\n }\r\n on(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n this.listeners_[eventType] = this.listeners_[eventType] || [];\r\n this.listeners_[eventType].push({ callback, context });\r\n const eventData = this.getInitialEvent(eventType);\r\n if (eventData) {\r\n callback.apply(context, eventData);\r\n }\r\n }\r\n off(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n const listeners = this.listeners_[eventType] || [];\r\n for (let i = 0; i < listeners.length; i++) {\r\n if (listeners[i].callback === callback &&\r\n (!context || context === listeners[i].context)) {\r\n listeners.splice(i, 1);\r\n return;\r\n }\r\n }\r\n }\r\n validateEventType_(eventType) {\r\n assert(this.allowedEvents_.find(et => {\r\n return et === eventType;\r\n }), 'Unknown event: ' + eventType);\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/**\r\n * Monitors online state (as reported by window.online/offline events).\r\n *\r\n * The expectation is that this could have many false positives (thinks we are online\r\n * when we're not), but no false negatives. So we can safely use it to determine when\r\n * we definitely cannot reach the internet.\r\n */\r\nclass OnlineMonitor extends EventEmitter {\r\n constructor() {\r\n super(['online']);\r\n this.online_ = true;\r\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\r\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\r\n // It would seem that the 'online' event does not always fire consistently. So we disable it\r\n // for Cordova.\r\n if (typeof window !== 'undefined' &&\r\n typeof window.addEventListener !== 'undefined' &&\r\n !isMobileCordova()) {\r\n window.addEventListener('online', () => {\r\n if (!this.online_) {\r\n this.online_ = true;\r\n this.trigger('online', true);\r\n }\r\n }, false);\r\n window.addEventListener('offline', () => {\r\n if (this.online_) {\r\n this.online_ = false;\r\n this.trigger('online', false);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new OnlineMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\r\n return [this.online_];\r\n }\r\n currentlyOnline() {\r\n return this.online_;\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/** Maximum key depth. */\r\nconst MAX_PATH_DEPTH = 32;\r\n/** Maximum number of (UTF8) bytes in a Firebase path. */\r\nconst MAX_PATH_LENGTH_BYTES = 768;\r\n/**\r\n * An immutable object representing a parsed path. It's immutable so that you\r\n * can pass them around to other functions without worrying about them changing\r\n * it.\r\n */\r\nclass Path {\r\n /**\r\n * @param pathOrString - Path string to parse, or another path, or the raw\r\n * tokens array\r\n */\r\n constructor(pathOrString, pieceNum) {\r\n if (pieceNum === void 0) {\r\n this.pieces_ = pathOrString.split('/');\r\n // Remove empty pieces.\r\n let copyTo = 0;\r\n for (let i = 0; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i].length > 0) {\r\n this.pieces_[copyTo] = this.pieces_[i];\r\n copyTo++;\r\n }\r\n }\r\n this.pieces_.length = copyTo;\r\n this.pieceNum_ = 0;\r\n }\r\n else {\r\n this.pieces_ = pathOrString;\r\n this.pieceNum_ = pieceNum;\r\n }\r\n }\r\n toString() {\r\n let pathString = '';\r\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i] !== '') {\r\n pathString += '/' + this.pieces_[i];\r\n }\r\n }\r\n return pathString || '/';\r\n }\r\n}\r\nfunction newEmptyPath() {\r\n return new Path('');\r\n}\r\nfunction pathGetFront(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n return path.pieces_[path.pieceNum_];\r\n}\r\n/**\r\n * @returns The number of segments in this path\r\n */\r\nfunction pathGetLength(path) {\r\n return path.pieces_.length - path.pieceNum_;\r\n}\r\nfunction pathPopFront(path) {\r\n let pieceNum = path.pieceNum_;\r\n if (pieceNum < path.pieces_.length) {\r\n pieceNum++;\r\n }\r\n return new Path(path.pieces_, pieceNum);\r\n}\r\nfunction pathGetBack(path) {\r\n if (path.pieceNum_ < path.pieces_.length) {\r\n return path.pieces_[path.pieces_.length - 1];\r\n }\r\n return null;\r\n}\r\nfunction pathToUrlEncodedString(path) {\r\n let pathString = '';\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n if (path.pieces_[i] !== '') {\r\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\r\n }\r\n }\r\n return pathString || '/';\r\n}\r\n/**\r\n * Shallow copy of the parts of the path.\r\n *\r\n */\r\nfunction pathSlice(path, begin = 0) {\r\n return path.pieces_.slice(path.pieceNum_ + begin);\r\n}\r\nfunction pathParent(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n return new Path(pieces, 0);\r\n}\r\nfunction pathChild(path, childPathObj) {\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n if (childPathObj instanceof Path) {\r\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\r\n pieces.push(childPathObj.pieces_[i]);\r\n }\r\n }\r\n else {\r\n const childPieces = childPathObj.split('/');\r\n for (let i = 0; i < childPieces.length; i++) {\r\n if (childPieces[i].length > 0) {\r\n pieces.push(childPieces[i]);\r\n }\r\n }\r\n }\r\n return new Path(pieces, 0);\r\n}\r\n/**\r\n * @returns True if there are no segments in this path\r\n */\r\nfunction pathIsEmpty(path) {\r\n return path.pieceNum_ >= path.pieces_.length;\r\n}\r\n/**\r\n * @returns The path from outerPath to innerPath\r\n */\r\nfunction newRelativePath(outerPath, innerPath) {\r\n const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);\r\n if (outer === null) {\r\n return innerPath;\r\n }\r\n else if (outer === inner) {\r\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\r\n }\r\n else {\r\n throw new Error('INTERNAL ERROR: innerPath (' +\r\n innerPath +\r\n ') is not within ' +\r\n 'outerPath (' +\r\n outerPath +\r\n ')');\r\n }\r\n}\r\n/**\r\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\r\n */\r\nfunction pathCompare(left, right) {\r\n const leftKeys = pathSlice(left, 0);\r\n const rightKeys = pathSlice(right, 0);\r\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\r\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\r\n if (cmp !== 0) {\r\n return cmp;\r\n }\r\n }\r\n if (leftKeys.length === rightKeys.length) {\r\n return 0;\r\n }\r\n return leftKeys.length < rightKeys.length ? -1 : 1;\r\n}\r\n/**\r\n * @returns true if paths are the same.\r\n */\r\nfunction pathEquals(path, other) {\r\n if (pathGetLength(path) !== pathGetLength(other)) {\r\n return false;\r\n }\r\n for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * @returns True if this path is a parent of (or the same as) other\r\n */\r\nfunction pathContains(path, other) {\r\n let i = path.pieceNum_;\r\n let j = other.pieceNum_;\r\n if (pathGetLength(path) > pathGetLength(other)) {\r\n return false;\r\n }\r\n while (i < path.pieces_.length) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n ++i;\r\n ++j;\r\n }\r\n return true;\r\n}\r\n/**\r\n * Dynamic (mutable) path used to count path lengths.\r\n *\r\n * This class is used to efficiently check paths for valid\r\n * length (in UTF8 bytes) and depth (used in path validation).\r\n *\r\n * Throws Error exception if path is ever invalid.\r\n *\r\n * The definition of a path always begins with '/'.\r\n */\r\nclass ValidationPath {\r\n /**\r\n * @param path - Initial Path.\r\n * @param errorPrefix_ - Prefix for any error messages.\r\n */\r\n constructor(path, errorPrefix_) {\r\n this.errorPrefix_ = errorPrefix_;\r\n this.parts_ = pathSlice(path, 0);\r\n /** Initialize to number of '/' chars needed in path. */\r\n this.byteLength_ = Math.max(1, this.parts_.length);\r\n for (let i = 0; i < this.parts_.length; i++) {\r\n this.byteLength_ += stringLength(this.parts_[i]);\r\n }\r\n validationPathCheckValid(this);\r\n }\r\n}\r\nfunction validationPathPush(validationPath, child) {\r\n // Count the needed '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ += 1;\r\n }\r\n validationPath.parts_.push(child);\r\n validationPath.byteLength_ += stringLength(child);\r\n validationPathCheckValid(validationPath);\r\n}\r\nfunction validationPathPop(validationPath) {\r\n const last = validationPath.parts_.pop();\r\n validationPath.byteLength_ -= stringLength(last);\r\n // Un-count the previous '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ -= 1;\r\n }\r\n}\r\nfunction validationPathCheckValid(validationPath) {\r\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'has a key path longer than ' +\r\n MAX_PATH_LENGTH_BYTES +\r\n ' bytes (' +\r\n validationPath.byteLength_ +\r\n ').');\r\n }\r\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'path specified exceeds the maximum depth that can be written (' +\r\n MAX_PATH_DEPTH +\r\n ') or object contains a cycle ' +\r\n validationPathToErrorString(validationPath));\r\n }\r\n}\r\n/**\r\n * String for use in error messages - uses '.' notation for path.\r\n */\r\nfunction validationPathToErrorString(validationPath) {\r\n if (validationPath.parts_.length === 0) {\r\n return '';\r\n }\r\n return \"in property '\" + validationPath.parts_.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\nclass VisibilityMonitor extends EventEmitter {\r\n constructor() {\r\n super(['visible']);\r\n let hidden;\r\n let visibilityChange;\r\n if (typeof document !== 'undefined' &&\r\n typeof document.addEventListener !== 'undefined') {\r\n if (typeof document['hidden'] !== 'undefined') {\r\n // Opera 12.10 and Firefox 18 and later support\r\n visibilityChange = 'visibilitychange';\r\n hidden = 'hidden';\r\n }\r\n else if (typeof document['mozHidden'] !== 'undefined') {\r\n visibilityChange = 'mozvisibilitychange';\r\n hidden = 'mozHidden';\r\n }\r\n else if (typeof document['msHidden'] !== 'undefined') {\r\n visibilityChange = 'msvisibilitychange';\r\n hidden = 'msHidden';\r\n }\r\n else if (typeof document['webkitHidden'] !== 'undefined') {\r\n visibilityChange = 'webkitvisibilitychange';\r\n hidden = 'webkitHidden';\r\n }\r\n }\r\n // Initially, we always assume we are visible. This ensures that in browsers\r\n // without page visibility support or in cases where we are never visible\r\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\r\n // reconnects\r\n this.visible_ = true;\r\n if (visibilityChange) {\r\n document.addEventListener(visibilityChange, () => {\r\n const visible = !document[hidden];\r\n if (visible !== this.visible_) {\r\n this.visible_ = visible;\r\n this.trigger('visible', visible);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new VisibilityMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\r\n return [this.visible_];\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\nconst RECONNECT_MIN_DELAY = 1000;\r\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\r\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\r\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\r\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\r\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\r\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\r\nconst INVALID_TOKEN_THRESHOLD = 3;\r\n/**\r\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\r\n *\r\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\r\n * in quotes to make sure the closure compiler does not minify them.\r\n */\r\nclass PersistentConnection extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param applicationId_ - The Firebase App ID for this project\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.onConnectStatus_ = onConnectStatus_;\r\n this.onServerInfoUpdate_ = onServerInfoUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n this.authOverride_ = authOverride_;\r\n // Used for diagnostic logging.\r\n this.id = PersistentConnection.nextPersistentConnectionId_++;\r\n this.log_ = logWrapper('p:' + this.id + ':');\r\n this.interruptReasons_ = {};\r\n this.listens = new Map();\r\n this.outstandingPuts_ = [];\r\n this.outstandingGets_ = [];\r\n this.outstandingPutCount_ = 0;\r\n this.outstandingGetCount_ = 0;\r\n this.onDisconnectRequestQueue_ = [];\r\n this.connected_ = false;\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\r\n this.securityDebugCallback_ = null;\r\n this.lastSessionId = null;\r\n this.establishConnectionTimer_ = null;\r\n this.visible_ = false;\r\n // Before we get connected, we keep a queue of pending messages to send.\r\n this.requestCBHash_ = {};\r\n this.requestNumber_ = 0;\r\n this.realtime_ = null;\r\n this.authToken_ = null;\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = false;\r\n this.invalidAuthTokenCount_ = 0;\r\n this.invalidAppCheckTokenCount_ = 0;\r\n this.firstConnection_ = true;\r\n this.lastConnectionAttemptTime_ = null;\r\n this.lastConnectionEstablishedTime_ = null;\r\n if (authOverride_ && !isNodeSdk()) {\r\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\r\n }\r\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\r\n if (repoInfo_.host.indexOf('fblocal') === -1) {\r\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\r\n }\r\n }\r\n sendRequest(action, body, onResponse) {\r\n const curReqNum = ++this.requestNumber_;\r\n const msg = { r: curReqNum, a: action, b: body };\r\n this.log_(stringify(msg));\r\n assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\r\n this.realtime_.sendRequest(msg);\r\n if (onResponse) {\r\n this.requestCBHash_[curReqNum] = onResponse;\r\n }\r\n }\r\n get(query) {\r\n this.initConnection_();\r\n const deferred = new Deferred();\r\n const request = {\r\n p: query._path.toString(),\r\n q: query._queryObject\r\n };\r\n const outstandingGet = {\r\n action: 'g',\r\n request,\r\n onComplete: (message) => {\r\n const payload = message['d'];\r\n if (message['s'] === 'ok') {\r\n deferred.resolve(payload);\r\n }\r\n else {\r\n deferred.reject(payload);\r\n }\r\n }\r\n };\r\n this.outstandingGets_.push(outstandingGet);\r\n this.outstandingGetCount_++;\r\n const index = this.outstandingGets_.length - 1;\r\n if (this.connected_) {\r\n this.sendGet_(index);\r\n }\r\n return deferred.promise;\r\n }\r\n listen(query, currentHashFn, tag, onComplete) {\r\n this.initConnection_();\r\n const queryId = query._queryIdentifier;\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + queryId);\r\n if (!this.listens.has(pathString)) {\r\n this.listens.set(pathString, new Map());\r\n }\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');\r\n assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);\r\n const listenSpec = {\r\n onComplete,\r\n hashFn: currentHashFn,\r\n query,\r\n tag\r\n };\r\n this.listens.get(pathString).set(queryId, listenSpec);\r\n if (this.connected_) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n sendGet_(index) {\r\n const get = this.outstandingGets_[index];\r\n this.sendRequest('g', get.request, (message) => {\r\n delete this.outstandingGets_[index];\r\n this.outstandingGetCount_--;\r\n if (this.outstandingGetCount_ === 0) {\r\n this.outstandingGets_ = [];\r\n }\r\n if (get.onComplete) {\r\n get.onComplete(message);\r\n }\r\n });\r\n }\r\n sendListen_(listenSpec) {\r\n const query = listenSpec.query;\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Listen on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'q';\r\n // Only bother to send query if it's non-default.\r\n if (listenSpec.tag) {\r\n req['q'] = query._queryObject;\r\n req['t'] = listenSpec.tag;\r\n }\r\n req[ /*hash*/'h'] = listenSpec.hashFn();\r\n this.sendRequest(action, req, (message) => {\r\n const payload = message[ /*data*/'d'];\r\n const status = message[ /*status*/'s'];\r\n // print warnings in any case...\r\n PersistentConnection.warnOnListenWarnings_(payload, query);\r\n const currentListenSpec = this.listens.get(pathString) &&\r\n this.listens.get(pathString).get(queryId);\r\n // only trigger actions if the listen hasn't been removed and readded\r\n if (currentListenSpec === listenSpec) {\r\n this.log_('listen response', message);\r\n if (status !== 'ok') {\r\n this.removeListen_(pathString, queryId);\r\n }\r\n if (listenSpec.onComplete) {\r\n listenSpec.onComplete(status, payload);\r\n }\r\n }\r\n });\r\n }\r\n static warnOnListenWarnings_(payload, query) {\r\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const warnings = safeGet(payload, 'w');\r\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\r\n const indexSpec = '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\r\n const indexPath = query._path.toString();\r\n warn(`Using an unspecified index. Your data will be downloaded and ` +\r\n `filtered on the client. Consider adding ${indexSpec} at ` +\r\n `${indexPath} to your security rules for better performance.`);\r\n }\r\n }\r\n }\r\n refreshAuthToken(token) {\r\n this.authToken_ = token;\r\n this.log_('Auth token refreshed');\r\n if (this.authToken_) {\r\n this.tryAuth();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\r\n //the credential so we dont become authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unauth', {}, () => { });\r\n }\r\n }\r\n this.reduceReconnectDelayIfAdminCredential_(token);\r\n }\r\n reduceReconnectDelayIfAdminCredential_(credential) {\r\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\r\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\r\n const isFirebaseSecret = credential && credential.length === 40;\r\n if (isFirebaseSecret || isAdmin(credential)) {\r\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n }\r\n }\r\n refreshAppCheckToken(token) {\r\n this.appCheckToken_ = token;\r\n this.log_('App check token refreshed');\r\n if (this.appCheckToken_) {\r\n this.tryAppCheck();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us.\r\n //If we're not connected, simply delete the credential so we dont become\r\n // authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unappeck', {}, () => { });\r\n }\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\r\n * a auth revoked (the connection is closed).\r\n */\r\n tryAuth() {\r\n if (this.connected_ && this.authToken_) {\r\n const token = this.authToken_;\r\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\r\n const requestData = { cred: token };\r\n if (this.authOverride_ === null) {\r\n requestData['noauth'] = true;\r\n }\r\n else if (typeof this.authOverride_ === 'object') {\r\n requestData['authvar'] = this.authOverride_;\r\n }\r\n this.sendRequest(authMethod, requestData, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (this.authToken_ === token) {\r\n if (status === 'ok') {\r\n this.invalidAuthTokenCount_ = 0;\r\n }\r\n else {\r\n // Triggers reconnect and force refresh for auth token\r\n this.onAuthRevoked_(status, data);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given token. If the authentication\r\n * attempt fails, it's triggered like the token was revoked (the connection is\r\n * closed).\r\n */\r\n tryAppCheck() {\r\n if (this.connected_ && this.appCheckToken_) {\r\n this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (status === 'ok') {\r\n this.invalidAppCheckTokenCount_ = 0;\r\n }\r\n else {\r\n this.onAppCheckRevoked_(status, data);\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n unlisten(query, tag) {\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && this.connected_) {\r\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\r\n }\r\n }\r\n sendUnlisten_(pathString, queryId, queryObj, tag) {\r\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'n';\r\n // Only bother sending queryId if it's non-default.\r\n if (tag) {\r\n req['q'] = queryObj;\r\n req['t'] = tag;\r\n }\r\n this.sendRequest(action, req);\r\n }\r\n onDisconnectPut(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('o', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'o',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectMerge(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('om', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'om',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectCancel(pathString, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'oc',\r\n data: null,\r\n onComplete\r\n });\r\n }\r\n }\r\n sendOnDisconnect_(action, pathString, data, onComplete) {\r\n const request = { /*path*/ p: pathString, /*data*/ d: data };\r\n this.log_('onDisconnect ' + action, request);\r\n this.sendRequest(action, request, (response) => {\r\n if (onComplete) {\r\n setTimeout(() => {\r\n onComplete(response[ /*status*/'s'], response[ /* data */'d']);\r\n }, Math.floor(0));\r\n }\r\n });\r\n }\r\n put(pathString, data, onComplete, hash) {\r\n this.putInternal('p', pathString, data, onComplete, hash);\r\n }\r\n merge(pathString, data, onComplete, hash) {\r\n this.putInternal('m', pathString, data, onComplete, hash);\r\n }\r\n putInternal(action, pathString, data, onComplete, hash) {\r\n this.initConnection_();\r\n const request = {\r\n /*path*/ p: pathString,\r\n /*data*/ d: data\r\n };\r\n if (hash !== undefined) {\r\n request[ /*hash*/'h'] = hash;\r\n }\r\n // TODO: Only keep track of the most recent put for a given path?\r\n this.outstandingPuts_.push({\r\n action,\r\n request,\r\n onComplete\r\n });\r\n this.outstandingPutCount_++;\r\n const index = this.outstandingPuts_.length - 1;\r\n if (this.connected_) {\r\n this.sendPut_(index);\r\n }\r\n else {\r\n this.log_('Buffering put: ' + pathString);\r\n }\r\n }\r\n sendPut_(index) {\r\n const action = this.outstandingPuts_[index].action;\r\n const request = this.outstandingPuts_[index].request;\r\n const onComplete = this.outstandingPuts_[index].onComplete;\r\n this.outstandingPuts_[index].queued = this.connected_;\r\n this.sendRequest(action, request, (message) => {\r\n this.log_(action + ' response', message);\r\n delete this.outstandingPuts_[index];\r\n this.outstandingPutCount_--;\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n if (onComplete) {\r\n onComplete(message[ /*status*/'s'], message[ /* data */'d']);\r\n }\r\n });\r\n }\r\n reportStats(stats) {\r\n // If we're not connected, we just drop the stats.\r\n if (this.connected_) {\r\n const request = { /*counters*/ c: stats };\r\n this.log_('reportStats', request);\r\n this.sendRequest(/*stats*/ 's', request, result => {\r\n const status = result[ /*status*/'s'];\r\n if (status !== 'ok') {\r\n const errorReason = result[ /* data */'d'];\r\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\r\n }\r\n });\r\n }\r\n }\r\n onDataMessage_(message) {\r\n if ('r' in message) {\r\n // this is a response\r\n this.log_('from server: ' + stringify(message));\r\n const reqNum = message['r'];\r\n const onResponse = this.requestCBHash_[reqNum];\r\n if (onResponse) {\r\n delete this.requestCBHash_[reqNum];\r\n onResponse(message[ /*body*/'b']);\r\n }\r\n }\r\n else if ('error' in message) {\r\n throw 'A server-side error has occurred: ' + message['error'];\r\n }\r\n else if ('a' in message) {\r\n // a and b are action and body, respectively\r\n this.onDataPush_(message['a'], message['b']);\r\n }\r\n }\r\n onDataPush_(action, body) {\r\n this.log_('handleServerMessage', action, body);\r\n if (action === 'd') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge*/ false, body['t']);\r\n }\r\n else if (action === 'm') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge=*/ true, body['t']);\r\n }\r\n else if (action === 'c') {\r\n this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);\r\n }\r\n else if (action === 'ac') {\r\n this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'apc') {\r\n this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'sd') {\r\n this.onSecurityDebugPacket_(body);\r\n }\r\n else {\r\n error('Unrecognized action received from server: ' +\r\n stringify(action) +\r\n '\\nAre you using the latest client?');\r\n }\r\n }\r\n onReady_(timestamp, sessionId) {\r\n this.log_('connection ready');\r\n this.connected_ = true;\r\n this.lastConnectionEstablishedTime_ = new Date().getTime();\r\n this.handleTimestamp_(timestamp);\r\n this.lastSessionId = sessionId;\r\n if (this.firstConnection_) {\r\n this.sendConnectStats_();\r\n }\r\n this.restoreState_();\r\n this.firstConnection_ = false;\r\n this.onConnectStatus_(true);\r\n }\r\n scheduleConnect_(timeout) {\r\n assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n }\r\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\r\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\r\n this.establishConnectionTimer_ = setTimeout(() => {\r\n this.establishConnectionTimer_ = null;\r\n this.establishConnection_();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(timeout));\r\n }\r\n initConnection_() {\r\n if (!this.realtime_ && this.firstConnection_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n onVisible_(visible) {\r\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\r\n if (visible &&\r\n !this.visible_ &&\r\n this.reconnectDelay_ === this.maxReconnectDelay_) {\r\n this.log_('Window became visible. Reducing delay.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n this.visible_ = visible;\r\n }\r\n onOnline_(online) {\r\n if (online) {\r\n this.log_('Browser went online.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n else {\r\n this.log_('Browser went offline. Killing connection.');\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n }\r\n }\r\n onRealtimeDisconnect_() {\r\n this.log_('data client disconnected');\r\n this.connected_ = false;\r\n this.realtime_ = null;\r\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\r\n this.cancelSentTransactions_();\r\n // Clear out the pending requests.\r\n this.requestCBHash_ = {};\r\n if (this.shouldReconnect_()) {\r\n if (!this.visible_) {\r\n this.log_(\"Window isn't visible. Delaying reconnect.\");\r\n this.reconnectDelay_ = this.maxReconnectDelay_;\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n }\r\n else if (this.lastConnectionEstablishedTime_) {\r\n // If we've been connected long enough, reset reconnect delay to minimum.\r\n const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\r\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n }\r\n this.lastConnectionEstablishedTime_ = null;\r\n }\r\n const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\r\n let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\r\n reconnectDelay = Math.random() * reconnectDelay;\r\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\r\n this.scheduleConnect_(reconnectDelay);\r\n // Adjust reconnect delay for next time.\r\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\r\n }\r\n this.onConnectStatus_(false);\r\n }\r\n async establishConnection_() {\r\n if (this.shouldReconnect_()) {\r\n this.log_('Making a connection attempt');\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n this.lastConnectionEstablishedTime_ = null;\r\n const onDataMessage = this.onDataMessage_.bind(this);\r\n const onReady = this.onReady_.bind(this);\r\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\r\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\r\n const lastSessionId = this.lastSessionId;\r\n let canceled = false;\r\n let connection = null;\r\n const closeFn = function () {\r\n if (connection) {\r\n connection.close();\r\n }\r\n else {\r\n canceled = true;\r\n onDisconnect();\r\n }\r\n };\r\n const sendRequestFn = function (msg) {\r\n assert(connection, \"sendRequest call when we're not connected not allowed.\");\r\n connection.sendRequest(msg);\r\n };\r\n this.realtime_ = {\r\n close: closeFn,\r\n sendRequest: sendRequestFn\r\n };\r\n const forceRefresh = this.forceTokenRefresh_;\r\n this.forceTokenRefresh_ = false;\r\n try {\r\n // First fetch auth and app check token, and establish connection after\r\n // fetching the token was successful\r\n const [authToken, appCheckToken] = await Promise.all([\r\n this.authTokenProvider_.getToken(forceRefresh),\r\n this.appCheckTokenProvider_.getToken(forceRefresh)\r\n ]);\r\n if (!canceled) {\r\n log('getToken() completed. Creating connection.');\r\n this.authToken_ = authToken && authToken.accessToken;\r\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\r\n connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, \r\n /* onKill= */ reason => {\r\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\r\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\r\n }, lastSessionId);\r\n }\r\n else {\r\n log('getToken() completed but was canceled');\r\n }\r\n }\r\n catch (error) {\r\n this.log_('Failed to get token: ' + error);\r\n if (!canceled) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\r\n // But getToken() may also just have temporarily failed, so we still want to\r\n // continue retrying.\r\n warn(error);\r\n }\r\n closeFn();\r\n }\r\n }\r\n }\r\n }\r\n interrupt(reason) {\r\n log('Interrupting connection for reason: ' + reason);\r\n this.interruptReasons_[reason] = true;\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n else {\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n this.establishConnectionTimer_ = null;\r\n }\r\n if (this.connected_) {\r\n this.onRealtimeDisconnect_();\r\n }\r\n }\r\n }\r\n resume(reason) {\r\n log('Resuming connection for reason: ' + reason);\r\n delete this.interruptReasons_[reason];\r\n if (isEmpty(this.interruptReasons_)) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n }\r\n handleTimestamp_(timestamp) {\r\n const delta = timestamp - new Date().getTime();\r\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\r\n }\r\n cancelSentTransactions_() {\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n const put = this.outstandingPuts_[i];\r\n if (put && /*hash*/ 'h' in put.request && put.queued) {\r\n if (put.onComplete) {\r\n put.onComplete('disconnect');\r\n }\r\n delete this.outstandingPuts_[i];\r\n this.outstandingPutCount_--;\r\n }\r\n }\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n }\r\n onListenRevoked_(pathString, query) {\r\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\r\n let queryId;\r\n if (!query) {\r\n queryId = 'default';\r\n }\r\n else {\r\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\r\n }\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && listen.onComplete) {\r\n listen.onComplete('permission_denied');\r\n }\r\n }\r\n removeListen_(pathString, queryId) {\r\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\r\n let listen;\r\n if (this.listens.has(normalizedPathString)) {\r\n const map = this.listens.get(normalizedPathString);\r\n listen = map.get(queryId);\r\n map.delete(queryId);\r\n if (map.size === 0) {\r\n this.listens.delete(normalizedPathString);\r\n }\r\n }\r\n else {\r\n // all listens for this path has already been removed\r\n listen = undefined;\r\n }\r\n return listen;\r\n }\r\n onAuthRevoked_(statusCode, explanation) {\r\n log('Auth token revoked: ' + statusCode + '/' + explanation);\r\n this.authToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n this.realtime_.close();\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAuthTokenCount_++;\r\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n // Set a long reconnect delay because recovery is unlikely\r\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n // Notify the auth token provider that the token is invalid, which will log\r\n // a warning\r\n this.authTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onAppCheckRevoked_(statusCode, explanation) {\r\n log('App check token revoked: ' + statusCode + '/' + explanation);\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n // Note: We don't close the connection as the developer may not have\r\n // enforcement enabled. The backend closes connections with enforcements.\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAppCheckTokenCount_++;\r\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n this.appCheckTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onSecurityDebugPacket_(body) {\r\n if (this.securityDebugCallback_) {\r\n this.securityDebugCallback_(body);\r\n }\r\n else {\r\n if ('msg' in body) {\r\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\r\n }\r\n }\r\n }\r\n restoreState_() {\r\n //Re-authenticate ourselves if we have a credential stored.\r\n this.tryAuth();\r\n this.tryAppCheck();\r\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\r\n // make sure to send listens before puts.\r\n for (const queries of this.listens.values()) {\r\n for (const listenSpec of queries.values()) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n if (this.outstandingPuts_[i]) {\r\n this.sendPut_(i);\r\n }\r\n }\r\n while (this.onDisconnectRequestQueue_.length) {\r\n const request = this.onDisconnectRequestQueue_.shift();\r\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\r\n }\r\n for (let i = 0; i < this.outstandingGets_.length; i++) {\r\n if (this.outstandingGets_[i]) {\r\n this.sendGet_(i);\r\n }\r\n }\r\n }\r\n /**\r\n * Sends client stats for first connection\r\n */\r\n sendConnectStats_() {\r\n const stats = {};\r\n let clientName = 'js';\r\n if (isNodeSdk()) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n clientName = 'admin_node';\r\n }\r\n else {\r\n clientName = 'node';\r\n }\r\n }\r\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\r\n if (isMobileCordova()) {\r\n stats['framework.cordova'] = 1;\r\n }\r\n else if (isReactNative()) {\r\n stats['framework.reactnative'] = 1;\r\n }\r\n this.reportStats(stats);\r\n }\r\n shouldReconnect_() {\r\n const online = OnlineMonitor.getInstance().currentlyOnline();\r\n return isEmpty(this.interruptReasons_) && online;\r\n }\r\n}\r\nPersistentConnection.nextPersistentConnectionId_ = 0;\r\n/**\r\n * Counter for number of connections created. Mainly used for tagging in the logs\r\n */\r\nPersistentConnection.nextConnectionId_ = 0;\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 NamedNode {\r\n constructor(name, node) {\r\n this.name = name;\r\n this.node = node;\r\n }\r\n static Wrap(name, node) {\r\n return new NamedNode(name, node);\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\nclass Index {\r\n /**\r\n * @returns A standalone comparison function for\r\n * this index\r\n */\r\n getCompare() {\r\n return this.compare.bind(this);\r\n }\r\n /**\r\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\r\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\r\n *\r\n *\r\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\r\n */\r\n indexedValueChanged(oldNode, newNode) {\r\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\r\n const newWrapped = new NamedNode(MIN_NAME, newNode);\r\n return this.compare(oldWrapped, newWrapped) !== 0;\r\n }\r\n /**\r\n * @returns a node wrapper that will sort equal to or less than\r\n * any other node wrapper, using this index\r\n */\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\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\nlet __EMPTY_NODE;\r\nclass KeyIndex extends Index {\r\n static get __EMPTY_NODE() {\r\n return __EMPTY_NODE;\r\n }\r\n static set __EMPTY_NODE(val) {\r\n __EMPTY_NODE = val;\r\n }\r\n compare(a, b) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n isDefinedOn(node) {\r\n // We could probably return true here (since every node has a key), but it's never called\r\n // so just leaving unimplemented for now.\r\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return false; // The key for a node never changes.\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // TODO: This should really be created once and cached in a static property, but\r\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\r\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\r\n }\r\n makePost(indexValue, name) {\r\n assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\r\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\r\n return new NamedNode(indexValue, __EMPTY_NODE);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.key';\r\n }\r\n}\r\nconst KEY_INDEX = new KeyIndex();\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 * An iterator over an LLRBNode.\r\n */\r\nclass SortedMapIterator {\r\n /**\r\n * @param node - Node to iterate.\r\n * @param isReverse_ - Whether or not to iterate in reverse\r\n */\r\n constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {\r\n this.isReverse_ = isReverse_;\r\n this.resultGenerator_ = resultGenerator_;\r\n this.nodeStack_ = [];\r\n let cmp = 1;\r\n while (!node.isEmpty()) {\r\n node = node;\r\n cmp = startKey ? comparator(node.key, startKey) : 1;\r\n // flip the comparison if we're going in reverse\r\n if (isReverse_) {\r\n cmp *= -1;\r\n }\r\n if (cmp < 0) {\r\n // This node is less than our start key. ignore it\r\n if (this.isReverse_) {\r\n node = node.left;\r\n }\r\n else {\r\n node = node.right;\r\n }\r\n }\r\n else if (cmp === 0) {\r\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\r\n this.nodeStack_.push(node);\r\n break;\r\n }\r\n else {\r\n // This node is greater than our start key, add it to the stack and move to the next one\r\n this.nodeStack_.push(node);\r\n if (this.isReverse_) {\r\n node = node.right;\r\n }\r\n else {\r\n node = node.left;\r\n }\r\n }\r\n }\r\n }\r\n getNext() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n let node = this.nodeStack_.pop();\r\n let result;\r\n if (this.resultGenerator_) {\r\n result = this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n result = { key: node.key, value: node.value };\r\n }\r\n if (this.isReverse_) {\r\n node = node.left;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.right;\r\n }\r\n }\r\n else {\r\n node = node.right;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.left;\r\n }\r\n }\r\n return result;\r\n }\r\n hasNext() {\r\n return this.nodeStack_.length > 0;\r\n }\r\n peek() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n const node = this.nodeStack_[this.nodeStack_.length - 1];\r\n if (this.resultGenerator_) {\r\n return this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n return { key: node.key, value: node.value };\r\n }\r\n }\r\n}\r\n/**\r\n * Represents a node in a Left-leaning Red-Black tree.\r\n */\r\nclass LLRBNode {\r\n /**\r\n * @param key - Key associated with this node.\r\n * @param value - Value associated with this node.\r\n * @param color - Whether this node is red.\r\n * @param left - Left child.\r\n * @param right - Right child.\r\n */\r\n constructor(key, value, color, left, right) {\r\n this.key = key;\r\n this.value = value;\r\n this.color = color != null ? color : LLRBNode.RED;\r\n this.left =\r\n left != null ? left : SortedMap.EMPTY_NODE;\r\n this.right =\r\n right != null ? right : SortedMap.EMPTY_NODE;\r\n }\r\n /**\r\n * Returns a copy of the current node, optionally replacing pieces of it.\r\n *\r\n * @param key - New key for the node, or null.\r\n * @param value - New value for the node, or null.\r\n * @param color - New color for the node, or null.\r\n * @param left - New left child for the node, or null.\r\n * @param right - New right child for the node, or null.\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return this.left.count() + 1 + this.right.count();\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return (this.left.inorderTraversal(action) ||\r\n !!action(this.key, this.value) ||\r\n this.right.inorderTraversal(action));\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return (this.right.reverseTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.left.reverseTraversal(action));\r\n }\r\n /**\r\n * @returns The minimum node in the tree.\r\n */\r\n min_() {\r\n if (this.left.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n return this.left.min_();\r\n }\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n minKey() {\r\n return this.min_().key;\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n maxKey() {\r\n if (this.right.isEmpty()) {\r\n return this.key;\r\n }\r\n else {\r\n return this.right.maxKey();\r\n }\r\n }\r\n /**\r\n * @param key - Key to insert.\r\n * @param value - Value to insert.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the key/value added.\r\n */\r\n insert(key, value, comparator) {\r\n let n = this;\r\n const cmp = comparator(key, n.key);\r\n if (cmp < 0) {\r\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\r\n }\r\n else if (cmp === 0) {\r\n n = n.copy(null, value, null, null, null);\r\n }\r\n else {\r\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns New tree, with the minimum key removed.\r\n */\r\n removeMin_() {\r\n if (this.left.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n let n = this;\r\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.removeMin_(), null);\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @param key - The key of the item to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the specified item removed.\r\n */\r\n remove(key, comparator) {\r\n let n, smallest;\r\n n = this;\r\n if (comparator(key, n.key) < 0) {\r\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\r\n }\r\n else {\r\n if (n.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\r\n n = n.moveRedRight_();\r\n }\r\n if (comparator(key, n.key) === 0) {\r\n if (n.right.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n else {\r\n smallest = n.right.min_();\r\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\r\n }\r\n }\r\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns Whether this is a RED node.\r\n */\r\n isRed_() {\r\n return this.color;\r\n }\r\n /**\r\n * @returns New tree after performing any needed rotations.\r\n */\r\n fixUp_() {\r\n let n = this;\r\n if (n.right.isRed_() && !n.left.isRed_()) {\r\n n = n.rotateLeft_();\r\n }\r\n if (n.left.isRed_() && n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (n.left.isRed_() && n.right.isRed_()) {\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedLeft.\r\n */\r\n moveRedLeft_() {\r\n let n = this.colorFlip_();\r\n if (n.right.left.isRed_()) {\r\n n = n.copy(null, null, null, null, n.right.rotateRight_());\r\n n = n.rotateLeft_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedRight.\r\n */\r\n moveRedRight_() {\r\n let n = this.colorFlip_();\r\n if (n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after rotateLeft.\r\n */\r\n rotateLeft_() {\r\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\r\n return this.right.copy(null, null, this.color, nl, null);\r\n }\r\n /**\r\n * @returns New tree, after rotateRight.\r\n */\r\n rotateRight_() {\r\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\r\n return this.left.copy(null, null, this.color, null, nr);\r\n }\r\n /**\r\n * @returns Newt ree, after colorFlip.\r\n */\r\n colorFlip_() {\r\n const left = this.left.copy(null, null, !this.left.color, null, null);\r\n const right = this.right.copy(null, null, !this.right.color, null, null);\r\n return this.copy(null, null, !this.color, left, right);\r\n }\r\n /**\r\n * For testing.\r\n *\r\n * @returns True if all is well.\r\n */\r\n checkMaxDepth_() {\r\n const blackDepth = this.check_();\r\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\r\n }\r\n check_() {\r\n if (this.isRed_() && this.left.isRed_()) {\r\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\r\n }\r\n if (this.right.isRed_()) {\r\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\r\n }\r\n const blackDepth = this.left.check_();\r\n if (blackDepth !== this.right.check_()) {\r\n throw new Error('Black depths differ');\r\n }\r\n else {\r\n return blackDepth + (this.isRed_() ? 0 : 1);\r\n }\r\n }\r\n}\r\nLLRBNode.RED = true;\r\nLLRBNode.BLACK = false;\r\n/**\r\n * Represents an empty node (a leaf node in the Red-Black Tree).\r\n */\r\nclass LLRBEmptyNode {\r\n /**\r\n * Returns a copy of the current node.\r\n *\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return this;\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key/value added.\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item added.\r\n */\r\n insert(key, value, comparator) {\r\n return new LLRBNode(key, value, null);\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item removed.\r\n */\r\n remove(key, comparator) {\r\n return this;\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return 0;\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return true;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n inorderTraversal(action) {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return false;\r\n }\r\n minKey() {\r\n return null;\r\n }\r\n maxKey() {\r\n return null;\r\n }\r\n check_() {\r\n return 0;\r\n }\r\n /**\r\n * @returns Whether this node is red.\r\n */\r\n isRed_() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\r\n * tree.\r\n */\r\nclass SortedMap {\r\n /**\r\n * @param comparator_ - Key comparator.\r\n * @param root_ - Optional root node for the map.\r\n */\r\n constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {\r\n this.comparator_ = comparator_;\r\n this.root_ = root_;\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key/value added or replaced.\r\n * (TODO: We should perhaps rename this method to 'put')\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @returns New map, with item added.\r\n */\r\n insert(key, value) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .insert(key, value, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @returns New map, with item removed.\r\n */\r\n remove(key) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .remove(key, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns the value of the node with the given key, or null.\r\n *\r\n * @param key - The key to look up.\r\n * @returns The value of the node with the given key, or null if the\r\n * key doesn't exist.\r\n */\r\n get(key) {\r\n let cmp;\r\n let node = this.root_;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n return node.value;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n node = node.right;\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns the key of the item *before* the specified key, or null if key is the first item.\r\n * @param key - The key to find the predecessor of\r\n * @returns The predecessor key.\r\n */\r\n getPredecessorKey(key) {\r\n let cmp, node = this.root_, rightParent = null;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n if (!node.left.isEmpty()) {\r\n node = node.left;\r\n while (!node.right.isEmpty()) {\r\n node = node.right;\r\n }\r\n return node.key;\r\n }\r\n else if (rightParent) {\r\n return rightParent.key;\r\n }\r\n else {\r\n return null; // first item.\r\n }\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n rightParent = node;\r\n node = node.right;\r\n }\r\n }\r\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\r\n }\r\n /**\r\n * @returns True if the map is empty.\r\n */\r\n isEmpty() {\r\n return this.root_.isEmpty();\r\n }\r\n /**\r\n * @returns The total number of nodes in the map.\r\n */\r\n count() {\r\n return this.root_.count();\r\n }\r\n /**\r\n * @returns The minimum key in the map.\r\n */\r\n minKey() {\r\n return this.root_.minKey();\r\n }\r\n /**\r\n * @returns The maximum key in the map.\r\n */\r\n maxKey() {\r\n return this.root_.maxKey();\r\n }\r\n /**\r\n * Traverses the map in key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return this.root_.inorderTraversal(action);\r\n }\r\n /**\r\n * Traverses the map in reverse key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns True if the traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return this.root_.reverseTraversal(action);\r\n }\r\n /**\r\n * Returns an iterator over the SortedMap.\r\n * @returns The iterator.\r\n */\r\n getIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\r\n }\r\n getIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\r\n }\r\n getReverseIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\r\n }\r\n getReverseIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\r\n }\r\n}\r\n/**\r\n * Always use the same empty node, to reduce memory.\r\n */\r\nSortedMap.EMPTY_NODE = new LLRBEmptyNode();\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 NAME_ONLY_COMPARATOR(left, right) {\r\n return nameCompare(left.name, right.name);\r\n}\r\nfunction NAME_COMPARATOR(left, right) {\r\n return nameCompare(left, right);\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\nlet MAX_NODE$2;\r\nfunction setMaxNode$1(val) {\r\n MAX_NODE$2 = val;\r\n}\r\nconst priorityHashText = function (priority) {\r\n if (typeof priority === 'number') {\r\n return 'number:' + doubleToIEEE754String(priority);\r\n }\r\n else {\r\n return 'string:' + priority;\r\n }\r\n};\r\n/**\r\n * Validates that a priority snapshot Node is valid.\r\n */\r\nconst validatePriorityNode = function (priorityNode) {\r\n if (priorityNode.isLeafNode()) {\r\n const val = priorityNode.val();\r\n assert(typeof val === 'string' ||\r\n typeof val === 'number' ||\r\n (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');\r\n }\r\n else {\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');\r\n }\r\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\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\nlet __childrenNodeConstructor;\r\n/**\r\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\r\n * implements Node and stores the value of the node (a string,\r\n * number, or boolean) accessible via getValue().\r\n */\r\nclass LeafNode {\r\n /**\r\n * @param value_ - The value to store in this leaf node. The object type is\r\n * possible in the event of a deferred value\r\n * @param priorityNode_ - The priority of this node.\r\n */\r\n constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n this.value_ = value_;\r\n this.priorityNode_ = priorityNode_;\r\n this.lazyHash_ = null;\r\n assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n static set __childrenNodeConstructor(val) {\r\n __childrenNodeConstructor = val;\r\n }\r\n static get __childrenNodeConstructor() {\r\n return __childrenNodeConstructor;\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return true;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n return new LeafNode(this.value_, newPriorityNode);\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n if (pathIsEmpty(path)) {\r\n return this;\r\n }\r\n else if (pathGetFront(path) === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n hasChild() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode) {\r\n return null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else if (newChildNode.isEmpty() && childName !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else if (newChildNode.isEmpty() && front !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return 0;\r\n }\r\n /** @inheritDoc */\r\n forEachChild(index, action) {\r\n return false;\r\n }\r\n val(exportFormat) {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n return {\r\n '.value': this.getValue(),\r\n '.priority': this.getPriority().val()\r\n };\r\n }\r\n else {\r\n return this.getValue();\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.priorityNode_.isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.priorityNode_.val()) +\r\n ':';\r\n }\r\n const type = typeof this.value_;\r\n toHash += type + ':';\r\n if (type === 'number') {\r\n toHash += doubleToIEEE754String(this.value_);\r\n }\r\n else {\r\n toHash += this.value_;\r\n }\r\n this.lazyHash_ = sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /**\r\n * Returns the value of the leaf node.\r\n * @returns The value of the node.\r\n */\r\n getValue() {\r\n return this.value_;\r\n }\r\n compareTo(other) {\r\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n return 1;\r\n }\r\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\r\n return -1;\r\n }\r\n else {\r\n assert(other.isLeafNode(), 'Unknown node type');\r\n return this.compareToLeafNode_(other);\r\n }\r\n }\r\n /**\r\n * Comparison specifically for two leaf nodes\r\n */\r\n compareToLeafNode_(otherLeaf) {\r\n const otherLeafType = typeof otherLeaf.value_;\r\n const thisLeafType = typeof this.value_;\r\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\r\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\r\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\r\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\r\n if (otherIndex === thisIndex) {\r\n // Same type, compare values\r\n if (thisLeafType === 'object') {\r\n // Deferred value nodes are all equal, but we should also never get to this point...\r\n return 0;\r\n }\r\n else {\r\n // Note that this works because true > false, all others are number or string comparisons\r\n if (this.value_ < otherLeaf.value_) {\r\n return -1;\r\n }\r\n else if (this.value_ === otherLeaf.value_) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n }\r\n else {\r\n return thisIndex - otherIndex;\r\n }\r\n }\r\n withIndex() {\r\n return this;\r\n }\r\n isIndexed() {\r\n return true;\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n const otherLeaf = other;\r\n return (this.value_ === otherLeaf.value_ &&\r\n this.priorityNode_.equals(otherLeaf.priorityNode_));\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n}\r\n/**\r\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\r\n * the same type, the comparison falls back to their value\r\n */\r\nLeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\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\nlet nodeFromJSON$1;\r\nlet MAX_NODE$1;\r\nfunction setNodeFromJSON(val) {\r\n nodeFromJSON$1 = val;\r\n}\r\nfunction setMaxNode(val) {\r\n MAX_NODE$1 = val;\r\n}\r\nclass PriorityIndex extends Index {\r\n compare(a, b) {\r\n const aPriority = a.node.getPriority();\r\n const bPriority = b.node.getPriority();\r\n const indexCmp = aPriority.compareTo(bPriority);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return !node.getPriority().isEmpty();\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.getPriority().equals(newNode.getPriority());\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));\r\n }\r\n makePost(indexValue, name) {\r\n const priorityNode = nodeFromJSON$1(indexValue);\r\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.priority';\r\n }\r\n}\r\nconst PRIORITY_INDEX = new PriorityIndex();\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 LOG_2 = Math.log(2);\r\nclass Base12Num {\r\n constructor(length) {\r\n const logBase2 = (num) => \r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n parseInt((Math.log(num) / LOG_2), 10);\r\n const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);\r\n this.count = logBase2(length + 1);\r\n this.current_ = this.count - 1;\r\n const mask = bitMask(this.count);\r\n this.bits_ = (length + 1) & mask;\r\n }\r\n nextBitIsOne() {\r\n //noinspection JSBitwiseOperatorUsage\r\n const result = !(this.bits_ & (0x1 << this.current_));\r\n this.current_--;\r\n return result;\r\n }\r\n}\r\n/**\r\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\r\n * function\r\n *\r\n * Uses the algorithm described in the paper linked here:\r\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\r\n *\r\n * @param childList - Unsorted list of children\r\n * @param cmp - The comparison method to be used\r\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\r\n * type is not NamedNode\r\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\r\n */\r\nconst buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\r\n childList.sort(cmp);\r\n const buildBalancedTree = function (low, high) {\r\n const length = high - low;\r\n let namedNode;\r\n let key;\r\n if (length === 0) {\r\n return null;\r\n }\r\n else if (length === 1) {\r\n namedNode = childList[low];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);\r\n }\r\n else {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const middle = parseInt((length / 2), 10) + low;\r\n const left = buildBalancedTree(low, middle);\r\n const right = buildBalancedTree(middle + 1, high);\r\n namedNode = childList[middle];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);\r\n }\r\n };\r\n const buildFrom12Array = function (base12) {\r\n let node = null;\r\n let root = null;\r\n let index = childList.length;\r\n const buildPennant = function (chunkSize, color) {\r\n const low = index - chunkSize;\r\n const high = index;\r\n index -= chunkSize;\r\n const childTree = buildBalancedTree(low + 1, high);\r\n const namedNode = childList[low];\r\n const key = keyFn ? keyFn(namedNode) : namedNode;\r\n attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));\r\n };\r\n const attachPennant = function (pennant) {\r\n if (node) {\r\n node.left = pennant;\r\n node = pennant;\r\n }\r\n else {\r\n root = pennant;\r\n node = pennant;\r\n }\r\n };\r\n for (let i = 0; i < base12.count; ++i) {\r\n const isOne = base12.nextBitIsOne();\r\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\r\n const chunkSize = Math.pow(2, base12.count - (i + 1));\r\n if (isOne) {\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n }\r\n else {\r\n // current == 2\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n buildPennant(chunkSize, LLRBNode.RED);\r\n }\r\n }\r\n return root;\r\n };\r\n const base12 = new Base12Num(childList.length);\r\n const root = buildFrom12Array(base12);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return new SortedMap(mapSortFn || cmp, root);\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\nlet _defaultIndexMap;\r\nconst fallbackObject = {};\r\nclass IndexMap {\r\n constructor(indexes_, indexSet_) {\r\n this.indexes_ = indexes_;\r\n this.indexSet_ = indexSet_;\r\n }\r\n /**\r\n * The default IndexMap for nodes without a priority\r\n */\r\n static get Default() {\r\n assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\r\n _defaultIndexMap =\r\n _defaultIndexMap ||\r\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });\r\n return _defaultIndexMap;\r\n }\r\n get(indexKey) {\r\n const sortedMap = safeGet(this.indexes_, indexKey);\r\n if (!sortedMap) {\r\n throw new Error('No index defined for ' + indexKey);\r\n }\r\n if (sortedMap instanceof SortedMap) {\r\n return sortedMap;\r\n }\r\n else {\r\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\r\n // regular child map\r\n return null;\r\n }\r\n }\r\n hasIndex(indexDefinition) {\r\n return contains(this.indexSet_, indexDefinition.toString());\r\n }\r\n addIndex(indexDefinition, existingChildren) {\r\n assert(indexDefinition !== KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\r\n const childList = [];\r\n let sawIndexedValue = false;\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n sawIndexedValue =\r\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\r\n childList.push(next);\r\n next = iter.getNext();\r\n }\r\n let newIndex;\r\n if (sawIndexedValue) {\r\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\r\n }\r\n else {\r\n newIndex = fallbackObject;\r\n }\r\n const indexName = indexDefinition.toString();\r\n const newIndexSet = Object.assign({}, this.indexSet_);\r\n newIndexSet[indexName] = indexDefinition;\r\n const newIndexes = Object.assign({}, this.indexes_);\r\n newIndexes[indexName] = newIndex;\r\n return new IndexMap(newIndexes, newIndexSet);\r\n }\r\n /**\r\n * Ensure that this node is properly tracked in any indexes that we're maintaining\r\n */\r\n addToIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {\r\n const index = safeGet(this.indexSet_, indexName);\r\n assert(index, 'Missing index implementation for ' + indexName);\r\n if (indexedChildren === fallbackObject) {\r\n // Check to see if we need to index everything\r\n if (index.isDefinedOn(namedNode.node)) {\r\n // We need to build this index\r\n const childList = [];\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n if (next.name !== namedNode.name) {\r\n childList.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n childList.push(namedNode);\r\n return buildChildSet(childList, index.getCompare());\r\n }\r\n else {\r\n // No change, this remains a fallback\r\n return fallbackObject;\r\n }\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n let newChildren = indexedChildren;\r\n if (existingSnap) {\r\n newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n return newChildren.insert(namedNode, namedNode.node);\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n /**\r\n * Create a new IndexMap instance with the given value removed\r\n */\r\n removeFromIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren) => {\r\n if (indexedChildren === fallbackObject) {\r\n // This is the fallback. Just return it, nothing to do in this case\r\n return indexedChildren;\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n if (existingSnap) {\r\n return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n else {\r\n // No record of this child\r\n return indexedChildren;\r\n }\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\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// TODO: For memory savings, don't store priorityNode_ if it's empty.\r\nlet EMPTY_NODE;\r\n/**\r\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\r\n * (i.e. nodes with children). It implements Node and stores the\r\n * list of children in the children property, sorted by child name.\r\n */\r\nclass ChildrenNode {\r\n /**\r\n * @param children_ - List of children of this node..\r\n * @param priorityNode_ - The priority of this node (as a snapshot node).\r\n */\r\n constructor(children_, priorityNode_, indexMap_) {\r\n this.children_ = children_;\r\n this.priorityNode_ = priorityNode_;\r\n this.indexMap_ = indexMap_;\r\n this.lazyHash_ = null;\r\n /**\r\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\r\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\r\n * class instead of an empty ChildrenNode.\r\n */\r\n if (this.priorityNode_) {\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n if (this.children_.isEmpty()) {\r\n assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\r\n }\r\n }\r\n static get EMPTY_NODE() {\r\n return (EMPTY_NODE ||\r\n (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_ || EMPTY_NODE;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n if (this.children_.isEmpty()) {\r\n // Don't allow priorities on empty nodes\r\n return this;\r\n }\r\n else {\r\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.getPriority();\r\n }\r\n else {\r\n const child = this.children_.get(childName);\r\n return child === null ? EMPTY_NODE : child;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return this;\r\n }\r\n return this.getImmediateChild(front).getChild(pathPopFront(path));\r\n }\r\n /** @inheritDoc */\r\n hasChild(childName) {\r\n return this.children_.get(childName) !== null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n assert(newChildNode, 'We should always be passing snapshot nodes');\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else {\r\n const namedNode = new NamedNode(childName, newChildNode);\r\n let newChildren, newIndexMap;\r\n if (newChildNode.isEmpty()) {\r\n newChildren = this.children_.remove(childName);\r\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\r\n }\r\n else {\r\n newChildren = this.children_.insert(childName, newChildNode);\r\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\r\n }\r\n const newPriority = newChildren.isEmpty()\r\n ? EMPTY_NODE\r\n : this.priorityNode_;\r\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else {\r\n assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);\r\n return this.updateImmediateChild(front, newImmediateChild);\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return this.children_.isEmpty();\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return this.children_.count();\r\n }\r\n /** @inheritDoc */\r\n val(exportFormat) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const obj = {};\r\n let numKeys = 0, maxKey = 0, allIntegerKeys = true;\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n obj[key] = childNode.val(exportFormat);\r\n numKeys++;\r\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\r\n maxKey = Math.max(maxKey, Number(key));\r\n }\r\n else {\r\n allIntegerKeys = false;\r\n }\r\n });\r\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\r\n // convert to array.\r\n const array = [];\r\n // eslint-disable-next-line guard-for-in\r\n for (const key in obj) {\r\n array[key] = obj[key];\r\n }\r\n return array;\r\n }\r\n else {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n obj['.priority'] = this.getPriority().val();\r\n }\r\n return obj;\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.getPriority().isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.getPriority().val()) +\r\n ':';\r\n }\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n const childHash = childNode.hash();\r\n if (childHash !== '') {\r\n toHash += ':' + key + ':' + childHash;\r\n }\r\n });\r\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode, index) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));\r\n return predecessor ? predecessor.name : null;\r\n }\r\n else {\r\n return this.children_.getPredecessorKey(childName);\r\n }\r\n }\r\n getFirstChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const minKey = idx.minKey();\r\n return minKey && minKey.name;\r\n }\r\n else {\r\n return this.children_.minKey();\r\n }\r\n }\r\n getFirstChild(indexDefinition) {\r\n const minKey = this.getFirstChildName(indexDefinition);\r\n if (minKey) {\r\n return new NamedNode(minKey, this.children_.get(minKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n /**\r\n * Given an index, return the key name of the largest value we have, according to that index\r\n */\r\n getLastChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const maxKey = idx.maxKey();\r\n return maxKey && maxKey.name;\r\n }\r\n else {\r\n return this.children_.maxKey();\r\n }\r\n }\r\n getLastChild(indexDefinition) {\r\n const maxKey = this.getLastChildName(indexDefinition);\r\n if (maxKey) {\r\n return new NamedNode(maxKey, this.children_.get(maxKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n forEachChild(index, action) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n return idx.inorderTraversal(wrappedNode => {\r\n return action(wrappedNode.name, wrappedNode.node);\r\n });\r\n }\r\n else {\r\n return this.children_.inorderTraversal(action);\r\n }\r\n }\r\n getIterator(indexDefinition) {\r\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\r\n }\r\n getIteratorFrom(startPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getIteratorFrom(startPost, key => key);\r\n }\r\n else {\r\n const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n getReverseIterator(indexDefinition) {\r\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\r\n }\r\n getReverseIteratorFrom(endPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getReverseIteratorFrom(endPost, key => {\r\n return key;\r\n });\r\n }\r\n else {\r\n const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n compareTo(other) {\r\n if (this.isEmpty()) {\r\n if (other.isEmpty()) {\r\n return 0;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (other.isLeafNode() || other.isEmpty()) {\r\n return 1;\r\n }\r\n else if (other === MAX_NODE) {\r\n return -1;\r\n }\r\n else {\r\n // Must be another node with children.\r\n return 0;\r\n }\r\n }\r\n withIndex(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX ||\r\n this.indexMap_.hasIndex(indexDefinition)) {\r\n return this;\r\n }\r\n else {\r\n const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\r\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\r\n }\r\n }\r\n isIndexed(index) {\r\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n const otherChildrenNode = other;\r\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\r\n return false;\r\n }\r\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\r\n const thisIter = this.getIterator(PRIORITY_INDEX);\r\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\r\n let thisCurrent = thisIter.getNext();\r\n let otherCurrent = otherIter.getNext();\r\n while (thisCurrent && otherCurrent) {\r\n if (thisCurrent.name !== otherCurrent.name ||\r\n !thisCurrent.node.equals(otherCurrent.node)) {\r\n return false;\r\n }\r\n thisCurrent = thisIter.getNext();\r\n otherCurrent = otherIter.getNext();\r\n }\r\n return thisCurrent === null && otherCurrent === null;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n }\r\n /**\r\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\r\n * instead.\r\n *\r\n */\r\n resolveIndex_(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX) {\r\n return null;\r\n }\r\n else {\r\n return this.indexMap_.get(indexDefinition.toString());\r\n }\r\n }\r\n}\r\nChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\r\nclass MaxNode extends ChildrenNode {\r\n constructor() {\r\n super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);\r\n }\r\n compareTo(other) {\r\n if (other === this) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n equals(other) {\r\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\r\n return other === this;\r\n }\r\n getPriority() {\r\n return this;\r\n }\r\n getImmediateChild(childName) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n isEmpty() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Marker that will sort higher than any other snapshot.\r\n */\r\nconst MAX_NODE = new MaxNode();\r\nObject.defineProperties(NamedNode, {\r\n MIN: {\r\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\r\n },\r\n MAX: {\r\n value: new NamedNode(MAX_NAME, MAX_NODE)\r\n }\r\n});\r\n/**\r\n * Reference Extensions\r\n */\r\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\r\nLeafNode.__childrenNodeConstructor = ChildrenNode;\r\nsetMaxNode$1(MAX_NODE);\r\nsetMaxNode(MAX_NODE);\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 USE_HINZE = true;\r\n/**\r\n * Constructs a snapshot node representing the passed JSON and returns it.\r\n * @param json - JSON to create a node for.\r\n * @param priority - Optional priority to use. This will be ignored if the\r\n * passed JSON contains a .priority property.\r\n */\r\nfunction nodeFromJSON(json, priority = null) {\r\n if (json === null) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n if (typeof json === 'object' && '.priority' in json) {\r\n priority = json['.priority'];\r\n }\r\n assert(priority === null ||\r\n typeof priority === 'string' ||\r\n typeof priority === 'number' ||\r\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\r\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\r\n json = json['.value'];\r\n }\r\n // Valid leaf nodes include non-objects or server-value wrapper objects\r\n if (typeof json !== 'object' || '.sv' in json) {\r\n const jsonLeaf = json;\r\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\r\n }\r\n if (!(json instanceof Array) && USE_HINZE) {\r\n const children = [];\r\n let childrenHavePriority = false;\r\n const hinzeJsonObj = json;\r\n each(hinzeJsonObj, (key, child) => {\r\n if (key.substring(0, 1) !== '.') {\r\n // Ignore metadata nodes\r\n const childNode = nodeFromJSON(child);\r\n if (!childNode.isEmpty()) {\r\n childrenHavePriority =\r\n childrenHavePriority || !childNode.getPriority().isEmpty();\r\n children.push(new NamedNode(key, childNode));\r\n }\r\n }\r\n });\r\n if (children.length === 0) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);\r\n if (childrenHavePriority) {\r\n const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));\r\n }\r\n else {\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);\r\n }\r\n }\r\n else {\r\n let node = ChildrenNode.EMPTY_NODE;\r\n each(json, (key, childData) => {\r\n if (contains(json, key)) {\r\n if (key.substring(0, 1) !== '.') {\r\n // ignore metadata nodes.\r\n const childNode = nodeFromJSON(childData);\r\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\r\n node = node.updateImmediateChild(key, childNode);\r\n }\r\n }\r\n }\r\n });\r\n return node.updatePriority(nodeFromJSON(priority));\r\n }\r\n}\r\nsetNodeFromJSON(nodeFromJSON);\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 PathIndex extends Index {\r\n constructor(indexPath_) {\r\n super();\r\n this.indexPath_ = indexPath_;\r\n assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\r\n }\r\n extractChild(snap) {\r\n return snap.getChild(this.indexPath_);\r\n }\r\n isDefinedOn(node) {\r\n return !node.getChild(this.indexPath_).isEmpty();\r\n }\r\n compare(a, b) {\r\n const aChild = this.extractChild(a.node);\r\n const bChild = this.extractChild(b.node);\r\n const indexCmp = aChild.compareTo(bChild);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\r\n return new NamedNode(name, node);\r\n }\r\n maxPost() {\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\r\n return new NamedNode(MAX_NAME, node);\r\n }\r\n toString() {\r\n return pathSlice(this.indexPath_, 0).join('/');\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\nclass ValueIndex extends Index {\r\n compare(a, b) {\r\n const indexCmp = a.node.compareTo(b.node);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return true;\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.equals(newNode);\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MAX;\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n return new NamedNode(name, valueNode);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.value';\r\n }\r\n}\r\nconst VALUE_INDEX = new ValueIndex();\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 changeValue(snapshotNode) {\r\n return { type: \"value\" /* ChangeType.VALUE */, snapshotNode };\r\n}\r\nfunction changeChildAdded(childName, snapshotNode) {\r\n return { type: \"child_added\" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };\r\n}\r\nfunction changeChildRemoved(childName, snapshotNode) {\r\n return { type: \"child_removed\" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };\r\n}\r\nfunction changeChildChanged(childName, snapshotNode, oldSnap) {\r\n return {\r\n type: \"child_changed\" /* ChangeType.CHILD_CHANGED */,\r\n snapshotNode,\r\n childName,\r\n oldSnap\r\n };\r\n}\r\nfunction changeChildMoved(childName, snapshotNode) {\r\n return { type: \"child_moved\" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };\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 * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\r\n */\r\nclass IndexedFilter {\r\n constructor(index_) {\r\n this.index_ = index_;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\r\n const oldChild = snap.getImmediateChild(key);\r\n // Check if anything actually changed.\r\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\r\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\r\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\r\n // to avoid treating these cases as \"nothing changed.\"\r\n if (oldChild.isEmpty() === newChild.isEmpty()) {\r\n // Nothing changed.\r\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\r\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\r\n return snap;\r\n }\r\n }\r\n if (optChangeAccumulator != null) {\r\n if (newChild.isEmpty()) {\r\n if (snap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));\r\n }\r\n else {\r\n assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\r\n }\r\n }\r\n else if (oldChild.isEmpty()) {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));\r\n }\r\n }\r\n if (snap.isLeafNode() && newChild.isEmpty()) {\r\n return snap;\r\n }\r\n else {\r\n // Make sure the node is indexed\r\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (optChangeAccumulator != null) {\r\n if (!oldSnap.isLeafNode()) {\r\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!newSnap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));\r\n }\r\n });\r\n }\r\n if (!newSnap.isLeafNode()) {\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (oldSnap.hasChild(key)) {\r\n const oldChild = oldSnap.getImmediateChild(key);\r\n if (!oldChild.equals(childNode)) {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));\r\n }\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));\r\n }\r\n });\r\n }\r\n }\r\n return newSnap.withIndex(this.index_);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n if (oldSnap.isEmpty()) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n else {\r\n return oldSnap.updatePriority(newPriority);\r\n }\r\n }\r\n filtersNodes() {\r\n return false;\r\n }\r\n getIndexedFilter() {\r\n return this;\r\n }\r\n getIndex() {\r\n return this.index_;\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/**\r\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\r\n */\r\nclass RangedFilter {\r\n constructor(params) {\r\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\r\n this.index_ = params.getIndex();\r\n this.startPost_ = RangedFilter.getStartPost_(params);\r\n this.endPost_ = RangedFilter.getEndPost_(params);\r\n this.startIsInclusive_ = !params.startAfterSet_;\r\n this.endIsInclusive_ = !params.endBeforeSet_;\r\n }\r\n getStartPost() {\r\n return this.startPost_;\r\n }\r\n getEndPost() {\r\n return this.endPost_;\r\n }\r\n matches(node) {\r\n const isWithinStart = this.startIsInclusive_\r\n ? this.index_.compare(this.getStartPost(), node) <= 0\r\n : this.index_.compare(this.getStartPost(), node) < 0;\r\n const isWithinEnd = this.endIsInclusive_\r\n ? this.index_.compare(node, this.getEndPost()) <= 0\r\n : this.index_.compare(node, this.getEndPost()) < 0;\r\n return isWithinStart && isWithinEnd;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (newSnap.isLeafNode()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n newSnap = ChildrenNode.EMPTY_NODE;\r\n }\r\n let filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n const self = this;\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!self.matches(new NamedNode(key, childNode))) {\r\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\r\n }\r\n });\r\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.indexedFilter_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n static getStartPost_(params) {\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\r\n }\r\n else {\r\n return params.getIndex().minPost();\r\n }\r\n }\r\n static getEndPost_(params) {\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\r\n }\r\n else {\r\n return params.getIndex().maxPost();\r\n }\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/**\r\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\r\n */\r\nclass LimitedFilter {\r\n constructor(params) {\r\n this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\r\n this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\r\n this.withinStartPost = (node) => {\r\n const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);\r\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\r\n };\r\n this.withinEndPost = (node) => {\r\n const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());\r\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\r\n };\r\n this.rangedFilter_ = new RangedFilter(params);\r\n this.index_ = params.getIndex();\r\n this.limit_ = params.getLimit();\r\n this.reverse_ = !params.isViewFromLeft();\r\n this.startIsInclusive_ = !params.startAfterSet_;\r\n this.endIsInclusive_ = !params.endBeforeSet_;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n if (snap.getImmediateChild(key).equals(newChild)) {\r\n // No change\r\n return snap;\r\n }\r\n else if (snap.numChildren() < this.limit_) {\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n else {\r\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n let filtered;\r\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n }\r\n else {\r\n if (this.limit_ * 2 < newSnap.numChildren() &&\r\n newSnap.isIndexed(this.index_)) {\r\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n // anchor to the startPost, endPost, or last element as appropriate\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\r\n }\r\n else {\r\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\r\n }\r\n let count = 0;\r\n while (iterator.hasNext() && count < this.limit_) {\r\n const next = iterator.getNext();\r\n if (!this.withinDirectionalStart(next)) {\r\n // if we have not reached the start, skip to the next element\r\n continue;\r\n }\r\n else if (!this.withinDirectionalEnd(next)) {\r\n // if we have reached the end, stop adding elements\r\n break;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, next.node);\r\n count++;\r\n }\r\n }\r\n }\r\n else {\r\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\r\n filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = filtered.getReverseIterator(this.index_);\r\n }\r\n else {\r\n iterator = filtered.getIterator(this.index_);\r\n }\r\n let count = 0;\r\n while (iterator.hasNext()) {\r\n const next = iterator.getNext();\r\n const inRange = count < this.limit_ &&\r\n this.withinDirectionalStart(next) &&\r\n this.withinDirectionalEnd(next);\r\n if (inRange) {\r\n count++;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n }\r\n }\r\n }\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.rangedFilter_.getIndexedFilter();\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {\r\n // TODO: rename all cache stuff etc to general snap terminology\r\n let cmp;\r\n if (this.reverse_) {\r\n const indexCmp = this.index_.getCompare();\r\n cmp = (a, b) => indexCmp(b, a);\r\n }\r\n else {\r\n cmp = this.index_.getCompare();\r\n }\r\n const oldEventCache = snap;\r\n assert(oldEventCache.numChildren() === this.limit_, '');\r\n const newChildNamedNode = new NamedNode(childKey, childSnap);\r\n const windowBoundary = this.reverse_\r\n ? oldEventCache.getFirstChild(this.index_)\r\n : oldEventCache.getLastChild(this.index_);\r\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\r\n if (oldEventCache.hasChild(childKey)) {\r\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\r\n let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\r\n while (nextChild != null &&\r\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {\r\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\r\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\r\n // the limited filter...\r\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\r\n }\r\n const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\r\n const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\r\n if (remainsInWindow) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));\r\n }\r\n return oldEventCache.updateImmediateChild(childKey, childSnap);\r\n }\r\n else {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));\r\n }\r\n const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\r\n const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\r\n if (nextChildInRange) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));\r\n }\r\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\r\n }\r\n else {\r\n return newEventCache;\r\n }\r\n }\r\n }\r\n else if (childSnap.isEmpty()) {\r\n // we're deleting a node, but it was not in the window, so ignore it\r\n return snap;\r\n }\r\n else if (inRange) {\r\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));\r\n changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));\r\n }\r\n return oldEventCache\r\n .updateImmediateChild(childKey, childSnap)\r\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n else {\r\n return snap;\r\n }\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/**\r\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\r\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\r\n * user-facing API level, so it is not done here.\r\n *\r\n * @internal\r\n */\r\nclass QueryParams {\r\n constructor() {\r\n this.limitSet_ = false;\r\n this.startSet_ = false;\r\n this.startNameSet_ = false;\r\n this.startAfterSet_ = false; // can only be true if startSet_ is true\r\n this.endSet_ = false;\r\n this.endNameSet_ = false;\r\n this.endBeforeSet_ = false; // can only be true if endSet_ is true\r\n this.limit_ = 0;\r\n this.viewFrom_ = '';\r\n this.indexStartValue_ = null;\r\n this.indexStartName_ = '';\r\n this.indexEndValue_ = null;\r\n this.indexEndName_ = '';\r\n this.index_ = PRIORITY_INDEX;\r\n }\r\n hasStart() {\r\n return this.startSet_;\r\n }\r\n /**\r\n * @returns True if it would return from left.\r\n */\r\n isViewFromLeft() {\r\n if (this.viewFrom_ === '') {\r\n // limit(), rather than limitToFirst or limitToLast was called.\r\n // This means that only one of startSet_ and endSet_ is true. Use them\r\n // to calculate which side of the view to anchor to. If neither is set,\r\n // anchor to the end.\r\n return this.startSet_;\r\n }\r\n else {\r\n return this.viewFrom_ === \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n }\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true\r\n */\r\n getIndexStartValue() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n return this.indexStartValue_;\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true.\r\n * Returns the starting key name for the range defined by these query parameters\r\n */\r\n getIndexStartName() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n if (this.startNameSet_) {\r\n return this.indexStartName_;\r\n }\r\n else {\r\n return MIN_NAME;\r\n }\r\n }\r\n hasEnd() {\r\n return this.endSet_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n */\r\n getIndexEndValue() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n return this.indexEndValue_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * Returns the end key name for the range defined by these query parameters\r\n */\r\n getIndexEndName() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n if (this.endNameSet_) {\r\n return this.indexEndName_;\r\n }\r\n else {\r\n return MAX_NAME;\r\n }\r\n }\r\n hasLimit() {\r\n return this.limitSet_;\r\n }\r\n /**\r\n * @returns True if a limit has been set and it has been explicitly anchored\r\n */\r\n hasAnchoredLimit() {\r\n return this.limitSet_ && this.viewFrom_ !== '';\r\n }\r\n /**\r\n * Only valid to call if hasLimit() returns true\r\n */\r\n getLimit() {\r\n assert(this.limitSet_, 'Only valid if limit has been set');\r\n return this.limit_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n loadsAllData() {\r\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\r\n }\r\n isDefault() {\r\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\r\n }\r\n copy() {\r\n const copy = new QueryParams();\r\n copy.limitSet_ = this.limitSet_;\r\n copy.limit_ = this.limit_;\r\n copy.startSet_ = this.startSet_;\r\n copy.startAfterSet_ = this.startAfterSet_;\r\n copy.indexStartValue_ = this.indexStartValue_;\r\n copy.startNameSet_ = this.startNameSet_;\r\n copy.indexStartName_ = this.indexStartName_;\r\n copy.endSet_ = this.endSet_;\r\n copy.endBeforeSet_ = this.endBeforeSet_;\r\n copy.indexEndValue_ = this.indexEndValue_;\r\n copy.endNameSet_ = this.endNameSet_;\r\n copy.indexEndName_ = this.indexEndName_;\r\n copy.index_ = this.index_;\r\n copy.viewFrom_ = this.viewFrom_;\r\n return copy;\r\n }\r\n}\r\nfunction queryParamsGetNodeFilter(queryParams) {\r\n if (queryParams.loadsAllData()) {\r\n return new IndexedFilter(queryParams.getIndex());\r\n }\r\n else if (queryParams.hasLimit()) {\r\n return new LimitedFilter(queryParams);\r\n }\r\n else {\r\n return new RangedFilter(queryParams);\r\n }\r\n}\r\nfunction queryParamsLimitToFirst(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n return newParams;\r\n}\r\nfunction queryParamsLimitToLast(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\r\n return newParams;\r\n}\r\nfunction queryParamsStartAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.startSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexStartValue_ = indexValue;\r\n if (key != null) {\r\n newParams.startNameSet_ = true;\r\n newParams.indexStartName_ = key;\r\n }\r\n else {\r\n newParams.startNameSet_ = false;\r\n newParams.indexStartName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsStartAfter(queryParams, indexValue, key) {\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX || !!key) {\r\n params = queryParamsStartAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\r\n }\r\n params.startAfterSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsEndAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.endSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexEndValue_ = indexValue;\r\n if (key !== undefined) {\r\n newParams.endNameSet_ = true;\r\n newParams.indexEndName_ = key;\r\n }\r\n else {\r\n newParams.endNameSet_ = false;\r\n newParams.indexEndName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsEndBefore(queryParams, indexValue, key) {\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX || !!key) {\r\n params = queryParamsEndAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\r\n }\r\n params.endBeforeSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsOrderBy(queryParams, index) {\r\n const newParams = queryParams.copy();\r\n newParams.index_ = index;\r\n return newParams;\r\n}\r\n/**\r\n * Returns a set of REST query string parameters representing this query.\r\n *\r\n * @returns query string parameters\r\n */\r\nfunction queryParamsToRestQueryStringParameters(queryParams) {\r\n const qs = {};\r\n if (queryParams.isDefault()) {\r\n return qs;\r\n }\r\n let orderBy;\r\n if (queryParams.index_ === PRIORITY_INDEX) {\r\n orderBy = \"$priority\" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;\r\n }\r\n else if (queryParams.index_ === VALUE_INDEX) {\r\n orderBy = \"$value\" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;\r\n }\r\n else if (queryParams.index_ === KEY_INDEX) {\r\n orderBy = \"$key\" /* REST_QUERY_CONSTANTS.KEY_INDEX */;\r\n }\r\n else {\r\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\r\n orderBy = queryParams.index_.toString();\r\n }\r\n qs[\"orderBy\" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);\r\n if (queryParams.startSet_) {\r\n const startParam = queryParams.startAfterSet_\r\n ? \"startAfter\" /* REST_QUERY_CONSTANTS.START_AFTER */\r\n : \"startAt\" /* REST_QUERY_CONSTANTS.START_AT */;\r\n qs[startParam] = stringify(queryParams.indexStartValue_);\r\n if (queryParams.startNameSet_) {\r\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\r\n }\r\n }\r\n if (queryParams.endSet_) {\r\n const endParam = queryParams.endBeforeSet_\r\n ? \"endBefore\" /* REST_QUERY_CONSTANTS.END_BEFORE */\r\n : \"endAt\" /* REST_QUERY_CONSTANTS.END_AT */;\r\n qs[endParam] = stringify(queryParams.indexEndValue_);\r\n if (queryParams.endNameSet_) {\r\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\r\n }\r\n }\r\n if (queryParams.limitSet_) {\r\n if (queryParams.isViewFromLeft()) {\r\n qs[\"limitToFirst\" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;\r\n }\r\n else {\r\n qs[\"limitToLast\" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;\r\n }\r\n }\r\n return qs;\r\n}\r\nfunction queryParamsGetQueryObject(queryParams) {\r\n const obj = {};\r\n if (queryParams.startSet_) {\r\n obj[\"sp\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =\r\n queryParams.indexStartValue_;\r\n if (queryParams.startNameSet_) {\r\n obj[\"sn\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =\r\n queryParams.indexStartName_;\r\n }\r\n obj[\"sin\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =\r\n !queryParams.startAfterSet_;\r\n }\r\n if (queryParams.endSet_) {\r\n obj[\"ep\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;\r\n if (queryParams.endNameSet_) {\r\n obj[\"en\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;\r\n }\r\n obj[\"ein\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =\r\n !queryParams.endBeforeSet_;\r\n }\r\n if (queryParams.limitSet_) {\r\n obj[\"l\" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;\r\n let viewFrom = queryParams.viewFrom_;\r\n if (viewFrom === '') {\r\n if (queryParams.isViewFromLeft()) {\r\n viewFrom = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n }\r\n else {\r\n viewFrom = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\r\n }\r\n }\r\n obj[\"vf\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;\r\n }\r\n // For now, priority index is the default, so we only specify if it's some other index\r\n if (queryParams.index_ !== PRIORITY_INDEX) {\r\n obj[\"i\" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();\r\n }\r\n return obj;\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 * An implementation of ServerActions that communicates with the server via REST requests.\r\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\r\n * persistent connection (using WebSockets or long-polling)\r\n */\r\nclass ReadonlyRestClient extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n /** @private {function(...[*])} */\r\n this.log_ = logWrapper('p:rest:');\r\n /**\r\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\r\n * that's been removed. :-/\r\n */\r\n this.listens_ = {};\r\n }\r\n reportStats(stats) {\r\n throw new Error('Method not implemented.');\r\n }\r\n static getListenId_(query, tag) {\r\n if (tag !== undefined) {\r\n return 'tag$' + tag;\r\n }\r\n else {\r\n assert(query._queryParams.isDefault(), \"should have a tag if it's not a default query.\");\r\n return query._path.toString();\r\n }\r\n }\r\n /** @inheritDoc */\r\n listen(query, currentHashFn, tag, onComplete) {\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\r\n // Mark this listener so we can tell if it's removed.\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n const thisListen = {};\r\n this.listens_[listenId] = thisListen;\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\r\n }\r\n if (safeGet(this.listens_, listenId) === thisListen) {\r\n let status;\r\n if (!error) {\r\n status = 'ok';\r\n }\r\n else if (error === 401) {\r\n status = 'permission_denied';\r\n }\r\n else {\r\n status = 'rest_error:' + error;\r\n }\r\n onComplete(status, null);\r\n }\r\n });\r\n }\r\n /** @inheritDoc */\r\n unlisten(query, tag) {\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n delete this.listens_[listenId];\r\n }\r\n get(query) {\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n const pathString = query._path.toString();\r\n const deferred = new Deferred();\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, \r\n /*isMerge=*/ false, \r\n /*tag=*/ null);\r\n deferred.resolve(data);\r\n }\r\n else {\r\n deferred.reject(new Error(data));\r\n }\r\n });\r\n return deferred.promise;\r\n }\r\n /** @inheritDoc */\r\n refreshAuthToken(token) {\r\n // no-op since we just always call getToken.\r\n }\r\n /**\r\n * Performs a REST request to the given path, with the provided query string parameters,\r\n * and any auth credentials we have.\r\n */\r\n restRequest_(pathString, queryStringParameters = {}, callback) {\r\n queryStringParameters['format'] = 'export';\r\n return Promise.all([\r\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\r\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\r\n ]).then(([authToken, appCheckToken]) => {\r\n if (authToken && authToken.accessToken) {\r\n queryStringParameters['auth'] = authToken.accessToken;\r\n }\r\n if (appCheckToken && appCheckToken.token) {\r\n queryStringParameters['ac'] = appCheckToken.token;\r\n }\r\n const url = (this.repoInfo_.secure ? 'https://' : 'http://') +\r\n this.repoInfo_.host +\r\n pathString +\r\n '?' +\r\n 'ns=' +\r\n this.repoInfo_.namespace +\r\n querystring(queryStringParameters);\r\n this.log_('Sending REST request for ' + url);\r\n const xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange = () => {\r\n if (callback && xhr.readyState === 4) {\r\n this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\r\n let res = null;\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n try {\r\n res = jsonEval(xhr.responseText);\r\n }\r\n catch (e) {\r\n warn('Failed to parse JSON response for ' +\r\n url +\r\n ': ' +\r\n xhr.responseText);\r\n }\r\n callback(null, res);\r\n }\r\n else {\r\n // 401 and 404 are expected.\r\n if (xhr.status !== 401 && xhr.status !== 404) {\r\n warn('Got unsuccessful REST response for ' +\r\n url +\r\n ' Status: ' +\r\n xhr.status);\r\n }\r\n callback(xhr.status);\r\n }\r\n callback = null;\r\n }\r\n };\r\n xhr.open('GET', url, /*asynchronous=*/ true);\r\n xhr.send();\r\n });\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/**\r\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\r\n */\r\nclass SnapshotHolder {\r\n constructor() {\r\n this.rootNode_ = ChildrenNode.EMPTY_NODE;\r\n }\r\n getNode(path) {\r\n return this.rootNode_.getChild(path);\r\n }\r\n updateSnapshot(path, newSnapshotNode) {\r\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\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\nfunction newSparseSnapshotTree() {\r\n return {\r\n value: null,\r\n children: new Map()\r\n };\r\n}\r\n/**\r\n * Stores the given node at the specified path. If there is already a node\r\n * at a shallower path, it merges the new data into that snapshot node.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @param data - The new data, or null.\r\n */\r\nfunction sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = data;\r\n sparseSnapshotTree.children.clear();\r\n }\r\n else if (sparseSnapshotTree.value !== null) {\r\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n if (!sparseSnapshotTree.children.has(childKey)) {\r\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\r\n }\r\n const child = sparseSnapshotTree.children.get(childKey);\r\n path = pathPopFront(path);\r\n sparseSnapshotTreeRemember(child, path, data);\r\n }\r\n}\r\n/**\r\n * Purge the data at path from the cache.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @returns True if this node should now be removed.\r\n */\r\nfunction sparseSnapshotTreeForget(sparseSnapshotTree, path) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = null;\r\n sparseSnapshotTree.children.clear();\r\n return true;\r\n }\r\n else {\r\n if (sparseSnapshotTree.value !== null) {\r\n if (sparseSnapshotTree.value.isLeafNode()) {\r\n // We're trying to forget a node that doesn't exist\r\n return false;\r\n }\r\n else {\r\n const value = sparseSnapshotTree.value;\r\n sparseSnapshotTree.value = null;\r\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\r\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\r\n });\r\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\r\n }\r\n }\r\n else if (sparseSnapshotTree.children.size > 0) {\r\n const childKey = pathGetFront(path);\r\n path = pathPopFront(path);\r\n if (sparseSnapshotTree.children.has(childKey)) {\r\n const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);\r\n if (safeToRemove) {\r\n sparseSnapshotTree.children.delete(childKey);\r\n }\r\n }\r\n return sparseSnapshotTree.children.size === 0;\r\n }\r\n else {\r\n return true;\r\n }\r\n }\r\n}\r\n/**\r\n * Recursively iterates through all of the stored tree and calls the\r\n * callback on each one.\r\n *\r\n * @param prefixPath - Path to look up node for.\r\n * @param func - The function to invoke for each tree.\r\n */\r\nfunction sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {\r\n if (sparseSnapshotTree.value !== null) {\r\n func(prefixPath, sparseSnapshotTree.value);\r\n }\r\n else {\r\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\r\n const path = new Path(prefixPath.toString() + '/' + key);\r\n sparseSnapshotTreeForEachTree(tree, path, func);\r\n });\r\n }\r\n}\r\n/**\r\n * Iterates through each immediate child and triggers the callback.\r\n * Only seems to be used in tests.\r\n *\r\n * @param func - The function to invoke for each child.\r\n */\r\nfunction sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {\r\n sparseSnapshotTree.children.forEach((tree, key) => {\r\n func(key, tree);\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/**\r\n * Returns the delta from the previous call to get stats.\r\n *\r\n * @param collection_ - The collection to \"listen\" to.\r\n */\r\nclass StatsListener {\r\n constructor(collection_) {\r\n this.collection_ = collection_;\r\n this.last_ = null;\r\n }\r\n get() {\r\n const newStats = this.collection_.get();\r\n const delta = Object.assign({}, newStats);\r\n if (this.last_) {\r\n each(this.last_, (stat, value) => {\r\n delta[stat] = delta[stat] - value;\r\n });\r\n }\r\n this.last_ = newStats;\r\n return delta;\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// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\r\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\r\n// seconds to try to ensure the Firebase connection is established / settled.\r\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\r\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\r\n// We'll continue to report stats on average every 5 minutes.\r\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\r\nclass StatsReporter {\r\n constructor(collection, server_) {\r\n this.server_ = server_;\r\n this.statsToReport_ = {};\r\n this.statsListener_ = new StatsListener(collection);\r\n const timeout = FIRST_STATS_MIN_TIME +\r\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\r\n }\r\n reportStats_() {\r\n const stats = this.statsListener_.get();\r\n const reportedStats = {};\r\n let haveStatsToReport = false;\r\n each(stats, (stat, value) => {\r\n if (value > 0 && contains(this.statsToReport_, stat)) {\r\n reportedStats[stat] = value;\r\n haveStatsToReport = true;\r\n }\r\n });\r\n if (haveStatsToReport) {\r\n this.server_.reportStats(reportedStats);\r\n }\r\n // queue our next run.\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\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/**\r\n *\r\n * @enum\r\n */\r\nvar OperationType;\r\n(function (OperationType) {\r\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\r\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\r\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\r\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\r\n})(OperationType || (OperationType = {}));\r\nfunction newOperationSourceUser() {\r\n return {\r\n fromUser: true,\r\n fromServer: false,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServer() {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServerTaggedQuery(queryId) {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId,\r\n tagged: true\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\nclass AckUserWrite {\r\n /**\r\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\r\n */\r\n constructor(\r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ affectedTree, \r\n /** @inheritDoc */ revert) {\r\n this.path = path;\r\n this.affectedTree = affectedTree;\r\n this.revert = revert;\r\n /** @inheritDoc */\r\n this.type = OperationType.ACK_USER_WRITE;\r\n /** @inheritDoc */\r\n this.source = newOperationSourceUser();\r\n }\r\n operationForChild(childName) {\r\n if (!pathIsEmpty(this.path)) {\r\n assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');\r\n return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);\r\n }\r\n else if (this.affectedTree.value != null) {\r\n assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\r\n // All child locations are affected as well; just return same operation.\r\n return this;\r\n }\r\n else {\r\n const childTree = this.affectedTree.subtree(new Path(childName));\r\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\r\n }\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\nclass ListenComplete {\r\n constructor(source, path) {\r\n this.source = source;\r\n this.path = path;\r\n /** @inheritDoc */\r\n this.type = OperationType.LISTEN_COMPLETE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new ListenComplete(this.source, newEmptyPath());\r\n }\r\n else {\r\n return new ListenComplete(this.source, pathPopFront(this.path));\r\n }\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\nclass Overwrite {\r\n constructor(source, path, snap) {\r\n this.source = source;\r\n this.path = path;\r\n this.snap = snap;\r\n /** @inheritDoc */\r\n this.type = OperationType.OVERWRITE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));\r\n }\r\n else {\r\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\r\n }\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\nclass Merge {\r\n constructor(\r\n /** @inheritDoc */ source, \r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ children) {\r\n this.source = source;\r\n this.path = path;\r\n this.children = children;\r\n /** @inheritDoc */\r\n this.type = OperationType.MERGE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n const childTree = this.children.subtree(new Path(childName));\r\n if (childTree.isEmpty()) {\r\n // This child is unaffected\r\n return null;\r\n }\r\n else if (childTree.value) {\r\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\r\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\r\n }\r\n else {\r\n // This is a merge at a deeper level\r\n return new Merge(this.source, newEmptyPath(), childTree);\r\n }\r\n }\r\n else {\r\n assert(pathGetFront(this.path) === childName, \"Can't get a merge for a child not on the path of the operation\");\r\n return new Merge(this.source, pathPopFront(this.path), this.children);\r\n }\r\n }\r\n toString() {\r\n return ('Operation(' +\r\n this.path +\r\n ': ' +\r\n this.source.toString() +\r\n ' merge: ' +\r\n this.children.toString() +\r\n ')');\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/**\r\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\r\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\r\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\r\n * whether a node potentially had children removed due to a filter.\r\n */\r\nclass CacheNode {\r\n constructor(node_, fullyInitialized_, filtered_) {\r\n this.node_ = node_;\r\n this.fullyInitialized_ = fullyInitialized_;\r\n this.filtered_ = filtered_;\r\n }\r\n /**\r\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\r\n */\r\n isFullyInitialized() {\r\n return this.fullyInitialized_;\r\n }\r\n /**\r\n * Returns whether this node is potentially missing children due to a filter applied to the node\r\n */\r\n isFiltered() {\r\n return this.filtered_;\r\n }\r\n isCompleteForPath(path) {\r\n if (pathIsEmpty(path)) {\r\n return this.isFullyInitialized() && !this.filtered_;\r\n }\r\n const childKey = pathGetFront(path);\r\n return this.isCompleteForChild(childKey);\r\n }\r\n isCompleteForChild(key) {\r\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\r\n }\r\n getNode() {\r\n return this.node_;\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/**\r\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\r\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\r\n * for details.\r\n *\r\n */\r\nclass EventGenerator {\r\n constructor(query_) {\r\n this.query_ = query_;\r\n this.index_ = this.query_._queryParams.getIndex();\r\n }\r\n}\r\n/**\r\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\r\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\r\n *\r\n * Notes:\r\n * - child_moved events will be synthesized at this time for any child_changed events that affect\r\n * our index.\r\n * - prevName will be calculated based on the index ordering.\r\n */\r\nfunction eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {\r\n const events = [];\r\n const moves = [];\r\n changes.forEach(change => {\r\n if (change.type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\r\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\r\n }\r\n });\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_removed\" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_added\" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_moved\" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_changed\" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"value\" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);\r\n return events;\r\n}\r\n/**\r\n * Given changes of a single change type, generate the corresponding events.\r\n */\r\nfunction eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {\r\n const filteredChanges = changes.filter(change => change.type === eventType);\r\n filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));\r\n filteredChanges.forEach(change => {\r\n const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);\r\n registrations.forEach(registration => {\r\n if (registration.respondsTo(change.type)) {\r\n events.push(registration.createEvent(materializedChange, eventGenerator.query_));\r\n }\r\n });\r\n });\r\n}\r\nfunction eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {\r\n if (change.type === 'value' || change.type === 'child_removed') {\r\n return change;\r\n }\r\n else {\r\n change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);\r\n return change;\r\n }\r\n}\r\nfunction eventGeneratorCompareChanges(eventGenerator, a, b) {\r\n if (a.childName == null || b.childName == null) {\r\n throw assertionError('Should only compare child_ events.');\r\n }\r\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\r\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\r\n return eventGenerator.index_.compare(aWrapped, bWrapped);\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 newViewCache(eventCache, serverCache) {\r\n return { eventCache, serverCache };\r\n}\r\nfunction viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {\r\n return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);\r\n}\r\nfunction viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {\r\n return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));\r\n}\r\nfunction viewCacheGetCompleteEventSnap(viewCache) {\r\n return viewCache.eventCache.isFullyInitialized()\r\n ? viewCache.eventCache.getNode()\r\n : null;\r\n}\r\nfunction viewCacheGetCompleteServerSnap(viewCache) {\r\n return viewCache.serverCache.isFullyInitialized()\r\n ? viewCache.serverCache.getNode()\r\n : 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\nlet emptyChildrenSingleton;\r\n/**\r\n * Singleton empty children collection.\r\n *\r\n */\r\nconst EmptyChildren = () => {\r\n if (!emptyChildrenSingleton) {\r\n emptyChildrenSingleton = new SortedMap(stringCompare);\r\n }\r\n return emptyChildrenSingleton;\r\n};\r\n/**\r\n * A tree with immutable elements.\r\n */\r\nclass ImmutableTree {\r\n constructor(value, children = EmptyChildren()) {\r\n this.value = value;\r\n this.children = children;\r\n }\r\n static fromObject(obj) {\r\n let tree = new ImmutableTree(null);\r\n each(obj, (childPath, childSnap) => {\r\n tree = tree.set(new Path(childPath), childSnap);\r\n });\r\n return tree;\r\n }\r\n /**\r\n * True if the value is empty and there are no children\r\n */\r\n isEmpty() {\r\n return this.value === null && this.children.isEmpty();\r\n }\r\n /**\r\n * Given a path and predicate, return the first node and the path to that node\r\n * where the predicate returns true.\r\n *\r\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\r\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\r\n *\r\n * @param relativePath - The remainder of the path\r\n * @param predicate - The predicate to satisfy to return a node\r\n */\r\n findRootMostMatchingPathAndValue(relativePath, predicate) {\r\n if (this.value != null && predicate(this.value)) {\r\n return { path: newEmptyPath(), value: this.value };\r\n }\r\n else {\r\n if (pathIsEmpty(relativePath)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child !== null) {\r\n const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);\r\n if (childExistingPathAndValue != null) {\r\n const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);\r\n return { path: fullPath, value: childExistingPathAndValue.value };\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * Find, if it exists, the shortest subpath of the given path that points a defined\r\n * value in the tree\r\n */\r\n findRootMostValueAndPath(relativePath) {\r\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\r\n }\r\n /**\r\n * @returns The subtree at the given path\r\n */\r\n subtree(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const childTree = this.children.get(front);\r\n if (childTree !== null) {\r\n return childTree.subtree(pathPopFront(relativePath));\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Sets a value at the specified path.\r\n *\r\n * @param relativePath - Path to set value at.\r\n * @param toSet - Value to set.\r\n * @returns Resulting tree.\r\n */\r\n set(relativePath, toSet) {\r\n if (pathIsEmpty(relativePath)) {\r\n return new ImmutableTree(toSet, this.children);\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.set(pathPopFront(relativePath), toSet);\r\n const newChildren = this.children.insert(front, newChild);\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Removes the value at the specified path.\r\n *\r\n * @param relativePath - Path to value to remove.\r\n * @returns Resulting tree.\r\n */\r\n remove(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n if (this.children.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(null, this.children);\r\n }\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n const newChild = child.remove(pathPopFront(relativePath));\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n if (this.value === null && newChildren.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n else {\r\n return this;\r\n }\r\n }\r\n }\r\n /**\r\n * Gets a value from the tree.\r\n *\r\n * @param relativePath - Path to get value for.\r\n * @returns Value at path, or null.\r\n */\r\n get(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this.value;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n return child.get(pathPopFront(relativePath));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n /**\r\n * Replace the subtree at the specified path with the given new tree.\r\n *\r\n * @param relativePath - Path to replace subtree for.\r\n * @param newTree - New tree.\r\n * @returns Resulting tree.\r\n */\r\n setTree(relativePath, newTree) {\r\n if (pathIsEmpty(relativePath)) {\r\n return newTree;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Performs a depth first fold on this tree. Transforms a tree into a single\r\n * value, given a function that operates on the path to a node, an optional\r\n * current value, and a map of child names to folded subtrees\r\n */\r\n fold(fn) {\r\n return this.fold_(newEmptyPath(), fn);\r\n }\r\n /**\r\n * Recursive helper for public-facing fold() method\r\n */\r\n fold_(pathSoFar, fn) {\r\n const accum = {};\r\n this.children.inorderTraversal((childKey, childTree) => {\r\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\r\n });\r\n return fn(pathSoFar, this.value, accum);\r\n }\r\n /**\r\n * Find the first matching value on the given path. Return the result of applying f to it.\r\n */\r\n findOnPath(path, f) {\r\n return this.findOnPath_(path, newEmptyPath(), f);\r\n }\r\n findOnPath_(pathToFollow, pathSoFar, f) {\r\n const result = this.value ? f(pathSoFar, this.value) : false;\r\n if (result) {\r\n return result;\r\n }\r\n else {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n foreachOnPath(path, f) {\r\n return this.foreachOnPath_(path, newEmptyPath(), f);\r\n }\r\n foreachOnPath_(pathToFollow, currentRelativePath, f) {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return this;\r\n }\r\n else {\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Calls the given function for each node in the tree that has a value.\r\n *\r\n * @param f - A function to be called with the path from the root of the tree to\r\n * a node, and the value at that node. Called in depth-first order.\r\n */\r\n foreach(f) {\r\n this.foreach_(newEmptyPath(), f);\r\n }\r\n foreach_(currentRelativePath, f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\r\n });\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n }\r\n foreachChild(f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value) {\r\n f(childName, childTree.value);\r\n }\r\n });\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/**\r\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\r\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\r\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\r\n * to reflect the write added.\r\n */\r\nclass CompoundWrite {\r\n constructor(writeTree_) {\r\n this.writeTree_ = writeTree_;\r\n }\r\n static empty() {\r\n return new CompoundWrite(new ImmutableTree(null));\r\n }\r\n}\r\nfunction compoundWriteAddWrite(compoundWrite, path, node) {\r\n if (pathIsEmpty(path)) {\r\n return new CompoundWrite(new ImmutableTree(node));\r\n }\r\n else {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n const rootMostPath = rootmost.path;\r\n let value = rootmost.value;\r\n const relativePath = newRelativePath(rootMostPath, path);\r\n value = value.updateChild(relativePath, node);\r\n return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));\r\n }\r\n else {\r\n const subtree = new ImmutableTree(node);\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n }\r\n}\r\nfunction compoundWriteAddWrites(compoundWrite, path, updates) {\r\n let newWrite = compoundWrite;\r\n each(updates, (childKey, node) => {\r\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\r\n });\r\n return newWrite;\r\n}\r\n/**\r\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\r\n * location, which must be removed by calling this method with that path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to remove.\r\n * @param path - The path at which a write and all deeper writes should be removed\r\n * @returns The new CompoundWrite with the removed path\r\n */\r\nfunction compoundWriteRemoveWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return CompoundWrite.empty();\r\n }\r\n else {\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n}\r\n/**\r\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\r\n * considered \"complete\".\r\n *\r\n * @param compoundWrite - The CompoundWrite to check.\r\n * @param path - The path to check for\r\n * @returns Whether there is a complete write at that path\r\n */\r\nfunction compoundWriteHasCompleteWrite(compoundWrite, path) {\r\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\r\n}\r\n/**\r\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\r\n * writes from deeper paths, but will return child nodes from a more shallow path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get the node from.\r\n * @param path - The path to get a complete write\r\n * @returns The node if complete at that path, or null otherwise.\r\n */\r\nfunction compoundWriteGetCompleteNode(compoundWrite, path) {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n return compoundWrite.writeTree_\r\n .get(rootmost.path)\r\n .getChild(newRelativePath(rootmost.path, path));\r\n }\r\n else {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Returns all children that are guaranteed to be a complete overwrite.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get children from.\r\n * @returns A list of all complete children.\r\n */\r\nfunction compoundWriteGetCompleteChildren(compoundWrite) {\r\n const children = [];\r\n const node = compoundWrite.writeTree_.value;\r\n if (node != null) {\r\n // If it's a leaf node, it has no children; so nothing to do.\r\n if (!node.isLeafNode()) {\r\n node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n children.push(new NamedNode(childName, childNode));\r\n });\r\n }\r\n }\r\n else {\r\n compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value != null) {\r\n children.push(new NamedNode(childName, childTree.value));\r\n }\r\n });\r\n }\r\n return children;\r\n}\r\nfunction compoundWriteChildCompoundWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return compoundWrite;\r\n }\r\n else {\r\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\r\n if (shadowingNode != null) {\r\n return new CompoundWrite(new ImmutableTree(shadowingNode));\r\n }\r\n else {\r\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\r\n * @returns Whether this CompoundWrite is empty\r\n */\r\nfunction compoundWriteIsEmpty(compoundWrite) {\r\n return compoundWrite.writeTree_.isEmpty();\r\n}\r\n/**\r\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\r\n * node\r\n * @param node - The node to apply this CompoundWrite to\r\n * @returns The node with all writes applied\r\n */\r\nfunction compoundWriteApply(compoundWrite, node) {\r\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\r\n}\r\nfunction applySubtreeWrite(relativePath, writeTree, node) {\r\n if (writeTree.value != null) {\r\n // Since there a write is always a leaf, we're done here\r\n return node.updateChild(relativePath, writeTree.value);\r\n }\r\n else {\r\n let priorityWrite = null;\r\n writeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (childKey === '.priority') {\r\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\r\n // to apply priorities to empty nodes that are later filled\r\n assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\r\n priorityWrite = childTree.value;\r\n }\r\n else {\r\n node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);\r\n }\r\n });\r\n // If there was a priority write, we only apply it if the node is not empty\r\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\r\n node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);\r\n }\r\n return node;\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/**\r\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\r\n *\r\n */\r\nfunction writeTreeChildWrites(writeTree, path) {\r\n return newWriteTreeRef(path, writeTree);\r\n}\r\n/**\r\n * Record a new overwrite from user code.\r\n *\r\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\r\n */\r\nfunction writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');\r\n if (visible === undefined) {\r\n visible = true;\r\n }\r\n writeTree.allWrites.push({\r\n path,\r\n snap,\r\n writeId,\r\n visible\r\n });\r\n if (visible) {\r\n writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);\r\n }\r\n writeTree.lastWriteId = writeId;\r\n}\r\n/**\r\n * Record a new merge from user code.\r\n */\r\nfunction writeTreeAddMerge(writeTree, path, changedChildren, writeId) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');\r\n writeTree.allWrites.push({\r\n path,\r\n children: changedChildren,\r\n writeId,\r\n visible: true\r\n });\r\n writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);\r\n writeTree.lastWriteId = writeId;\r\n}\r\nfunction writeTreeGetWrite(writeTree, writeId) {\r\n for (let i = 0; i < writeTree.allWrites.length; i++) {\r\n const record = writeTree.allWrites[i];\r\n if (record.writeId === writeId) {\r\n return record;\r\n }\r\n }\r\n return null;\r\n}\r\n/**\r\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\r\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\r\n *\r\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\r\n * events as a result).\r\n */\r\nfunction writeTreeRemoveWrite(writeTree, writeId) {\r\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\r\n // out of order.\r\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\r\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\r\n const idx = writeTree.allWrites.findIndex(s => {\r\n return s.writeId === writeId;\r\n });\r\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\r\n const writeToRemove = writeTree.allWrites[idx];\r\n writeTree.allWrites.splice(idx, 1);\r\n let removedWriteWasVisible = writeToRemove.visible;\r\n let removedWriteOverlapsWithOtherWrites = false;\r\n let i = writeTree.allWrites.length - 1;\r\n while (removedWriteWasVisible && i >= 0) {\r\n const currentWrite = writeTree.allWrites[i];\r\n if (currentWrite.visible) {\r\n if (i >= idx &&\r\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {\r\n // The removed write was completely shadowed by a subsequent write.\r\n removedWriteWasVisible = false;\r\n }\r\n else if (pathContains(writeToRemove.path, currentWrite.path)) {\r\n // Either we're covering some writes or they're covering part of us (depending on which came first).\r\n removedWriteOverlapsWithOtherWrites = true;\r\n }\r\n }\r\n i--;\r\n }\r\n if (!removedWriteWasVisible) {\r\n return false;\r\n }\r\n else if (removedWriteOverlapsWithOtherWrites) {\r\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\r\n writeTreeResetTree_(writeTree);\r\n return true;\r\n }\r\n else {\r\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\r\n if (writeToRemove.snap) {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);\r\n }\r\n else {\r\n const children = writeToRemove.children;\r\n each(children, (childName) => {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));\r\n });\r\n }\r\n return true;\r\n }\r\n}\r\nfunction writeTreeRecordContainsPath_(writeRecord, path) {\r\n if (writeRecord.snap) {\r\n return pathContains(writeRecord.path, path);\r\n }\r\n else {\r\n for (const childName in writeRecord.children) {\r\n if (writeRecord.children.hasOwnProperty(childName) &&\r\n pathContains(pathChild(writeRecord.path, childName), path)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n}\r\n/**\r\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\r\n */\r\nfunction writeTreeResetTree_(writeTree) {\r\n writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());\r\n if (writeTree.allWrites.length > 0) {\r\n writeTree.lastWriteId =\r\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\r\n }\r\n else {\r\n writeTree.lastWriteId = -1;\r\n }\r\n}\r\n/**\r\n * The default filter used when constructing the tree. Keep everything that's visible.\r\n */\r\nfunction writeTreeDefaultFilter_(write) {\r\n return write.visible;\r\n}\r\n/**\r\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\r\n * event data at that path.\r\n */\r\nfunction writeTreeLayerTree_(writes, filter, treeRoot) {\r\n let compoundWrite = CompoundWrite.empty();\r\n for (let i = 0; i < writes.length; ++i) {\r\n const write = writes[i];\r\n // Theory, a later set will either:\r\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\r\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\r\n if (filter(write)) {\r\n const writePath = write.path;\r\n let relativePath;\r\n if (write.snap) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));\r\n }\r\n else ;\r\n }\r\n else if (write.children) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n if (pathIsEmpty(relativePath)) {\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);\r\n }\r\n else {\r\n const child = safeGet(write.children, pathGetFront(relativePath));\r\n if (child) {\r\n // There exists a child in this node that matches the root path\r\n const deepNode = child.getChild(pathPopFront(relativePath));\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);\r\n }\r\n }\r\n }\r\n else ;\r\n }\r\n else {\r\n throw assertionError('WriteRecord should have .snap or .children');\r\n }\r\n }\r\n }\r\n return compoundWrite;\r\n}\r\n/**\r\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\r\n * writes), attempt to calculate a complete snapshot for the given path\r\n *\r\n * @param writeIdsToExclude - An optional set to be excluded\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n if (!writeIdsToExclude && !includeHiddenWrites) {\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (compoundWriteIsEmpty(subMerge)) {\r\n return completeServerCache;\r\n }\r\n else if (completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {\r\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\r\n return null;\r\n }\r\n else {\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(subMerge, layeredCache);\r\n }\r\n }\r\n }\r\n else {\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\r\n return completeServerCache;\r\n }\r\n else {\r\n // If the server cache is null, and we don't have a complete cache, we need to return null\r\n if (!includeHiddenWrites &&\r\n completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {\r\n return null;\r\n }\r\n else {\r\n const filter = function (write) {\r\n return ((write.visible || includeHiddenWrites) &&\r\n (!writeIdsToExclude ||\r\n !~writeIdsToExclude.indexOf(write.writeId)) &&\r\n (pathContains(write.path, treePath) ||\r\n pathContains(treePath, write.path)));\r\n };\r\n const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(mergeAtPath, layeredCache);\r\n }\r\n }\r\n }\r\n}\r\n/**\r\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\r\n * Used when creating new views, to pre-fill their complete event children snapshot.\r\n */\r\nfunction writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {\r\n let completeChildren = ChildrenNode.EMPTY_NODE;\r\n const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (topLevelSet) {\r\n if (!topLevelSet.isLeafNode()) {\r\n // we're shadowing everything. Return the children.\r\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\r\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\r\n });\r\n }\r\n return completeChildren;\r\n }\r\n else if (completeServerChildren) {\r\n // Layer any children we have on top of this\r\n // We know we don't have a top-level set, so just enumerate existing children\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);\r\n completeChildren = completeChildren.updateImmediateChild(childName, node);\r\n });\r\n // Add any complete children we have from the set\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n else {\r\n // We don't have anything to layer on top of. Layer on any children we have\r\n // Note that we can return an empty snap if we have a defined delete\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n}\r\n/**\r\n * Given that the underlying server data has updated, determine what, if anything, needs to be\r\n * applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist\r\n */\r\nfunction writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {\r\n assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\r\n const path = pathChild(treePath, childPath);\r\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\r\n // At this point we can probably guarantee that we're in case 2, meaning no events\r\n // May need to check visibility while doing the findRootMostValueAndPath call\r\n return null;\r\n }\r\n else {\r\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n if (compoundWriteIsEmpty(childMerge)) {\r\n // We're not shadowing at all. Case 1\r\n return existingServerSnap.getChild(childPath);\r\n }\r\n else {\r\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\r\n // However this is tricky to find out, since user updates don't necessary change the server\r\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\r\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\r\n // only check if the updates change the serverNode.\r\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\r\n return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {\r\n const path = pathChild(treePath, childKey);\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n if (existingServerSnap.isCompleteForChild(childKey)) {\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n */\r\nfunction writeTreeShadowingWrite(writeTree, path) {\r\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window.\r\n */\r\nfunction writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {\r\n let toIterate;\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\r\n if (shadowingNode != null) {\r\n toIterate = shadowingNode;\r\n }\r\n else if (completeServerData != null) {\r\n toIterate = compoundWriteApply(merge, completeServerData);\r\n }\r\n else {\r\n // no children to iterate on\r\n return [];\r\n }\r\n toIterate = toIterate.withIndex(index);\r\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\r\n const nodes = [];\r\n const cmp = index.getCompare();\r\n const iter = reverse\r\n ? toIterate.getReverseIteratorFrom(startPost, index)\r\n : toIterate.getIteratorFrom(startPost, index);\r\n let next = iter.getNext();\r\n while (next && nodes.length < count) {\r\n if (cmp(next, startPost) !== 0) {\r\n nodes.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n return nodes;\r\n }\r\n else {\r\n return [];\r\n }\r\n}\r\nfunction newWriteTree() {\r\n return {\r\n visibleWrites: CompoundWrite.empty(),\r\n allWrites: [],\r\n lastWriteId: -1\r\n };\r\n}\r\n/**\r\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\r\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\r\n * can lead to a more expensive calculation.\r\n *\r\n * @param writeIdsToExclude - Optional writes to exclude.\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);\r\n}\r\n/**\r\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\r\n * mix of the given server data and write data.\r\n *\r\n */\r\nfunction writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {\r\n return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);\r\n}\r\n/**\r\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\r\n * if anything, needs to be applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events should be raised\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\r\n *\r\n *\r\n */\r\nfunction writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {\r\n return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n *\r\n */\r\nfunction writeTreeRefShadowingWrite(writeTreeRef, path) {\r\n return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window\r\n */\r\nfunction writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {\r\n return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {\r\n return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);\r\n}\r\n/**\r\n * Return a WriteTreeRef for a child.\r\n */\r\nfunction writeTreeRefChild(writeTreeRef, childName) {\r\n return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);\r\n}\r\nfunction newWriteTreeRef(path, writeTree) {\r\n return {\r\n treePath: path,\r\n writeTree\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\nclass ChildChangeAccumulator {\r\n constructor() {\r\n this.changeMap = new Map();\r\n }\r\n trackChildChange(change) {\r\n const type = change.type;\r\n const childKey = change.childName;\r\n assert(type === \"child_added\" /* ChangeType.CHILD_ADDED */ ||\r\n type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ ||\r\n type === \"child_removed\" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');\r\n assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\r\n const oldChange = this.changeMap.get(childKey);\r\n if (oldChange) {\r\n const oldType = oldChange.type;\r\n if (type === \"child_added\" /* ChangeType.CHILD_ADDED */ &&\r\n oldType === \"child_removed\" /* ChangeType.CHILD_REMOVED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));\r\n }\r\n else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\r\n oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\r\n this.changeMap.delete(childKey);\r\n }\r\n else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\r\n oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));\r\n }\r\n else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\r\n this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));\r\n }\r\n else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));\r\n }\r\n else {\r\n throw assertionError('Illegal combination of changes: ' +\r\n change +\r\n ' occurred after ' +\r\n oldChange);\r\n }\r\n }\r\n else {\r\n this.changeMap.set(childKey, change);\r\n }\r\n }\r\n getChanges() {\r\n return Array.from(this.changeMap.values());\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/**\r\n * An implementation of CompleteChildSource that never returns any additional children\r\n */\r\n// eslint-disable-next-line @typescript-eslint/naming-convention\r\nclass NoCompleteChildSource_ {\r\n getCompleteChild(childKey) {\r\n return null;\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Singleton instance.\r\n */\r\nconst NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\r\n/**\r\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\r\n * old event caches available to calculate complete children.\r\n */\r\nclass WriteTreeCompleteChildSource {\r\n constructor(writes_, viewCache_, optCompleteServerCache_ = null) {\r\n this.writes_ = writes_;\r\n this.viewCache_ = viewCache_;\r\n this.optCompleteServerCache_ = optCompleteServerCache_;\r\n }\r\n getCompleteChild(childKey) {\r\n const node = this.viewCache_.eventCache;\r\n if (node.isCompleteForChild(childKey)) {\r\n return node.getNode().getImmediateChild(childKey);\r\n }\r\n else {\r\n const serverNode = this.optCompleteServerCache_ != null\r\n ? new CacheNode(this.optCompleteServerCache_, true, false)\r\n : this.viewCache_.serverCache;\r\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\r\n }\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n const completeServerData = this.optCompleteServerCache_ != null\r\n ? this.optCompleteServerCache_\r\n : viewCacheGetCompleteServerSnap(this.viewCache_);\r\n const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);\r\n if (nodes.length === 0) {\r\n return null;\r\n }\r\n else {\r\n return nodes[0];\r\n }\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\nfunction newViewProcessor(filter) {\r\n return { filter };\r\n}\r\nfunction viewProcessorAssertIndexed(viewProcessor, viewCache) {\r\n assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');\r\n assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');\r\n}\r\nfunction viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {\r\n const accumulator = new ChildChangeAccumulator();\r\n let newViewCache, filterServerNode;\r\n if (operation.type === OperationType.OVERWRITE) {\r\n const overwrite = operation;\r\n if (overwrite.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(overwrite.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered and the\r\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\r\n // again\r\n filterServerNode =\r\n overwrite.source.tagged ||\r\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\r\n newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.MERGE) {\r\n const merge = operation;\r\n if (merge.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(merge.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered\r\n filterServerNode =\r\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\r\n newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.ACK_USER_WRITE) {\r\n const ackUserWrite = operation;\r\n if (!ackUserWrite.revert) {\r\n newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.LISTEN_COMPLETE) {\r\n newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);\r\n }\r\n else {\r\n throw assertionError('Unknown operation type: ' + operation.type);\r\n }\r\n const changes = accumulator.getChanges();\r\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\r\n return { viewCache: newViewCache, changes };\r\n}\r\nfunction viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {\r\n const eventSnap = newViewCache.eventCache;\r\n if (eventSnap.isFullyInitialized()) {\r\n const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\r\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\r\n if (accumulator.length > 0 ||\r\n !oldViewCache.eventCache.isFullyInitialized() ||\r\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\r\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {\r\n accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));\r\n }\r\n }\r\n}\r\nfunction viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {\r\n const oldEventSnap = viewCache.eventCache;\r\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\r\n // we have a shadowing write, ignore changes\r\n return viewCache;\r\n }\r\n else {\r\n let newEventCache, serverNode;\r\n if (pathIsEmpty(changePath)) {\r\n // TODO: figure out how this plays with \"sliding ack windows\"\r\n assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');\r\n if (viewCache.serverCache.isFiltered()) {\r\n // We need to special case this, because we need to only apply writes to complete children, or\r\n // we might end up raising events for incomplete children. If the server data is filtered deep\r\n // writes cannot be guaranteed to be complete\r\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\r\n const completeChildren = serverCache instanceof ChildrenNode\r\n ? serverCache\r\n : ChildrenNode.EMPTY_NODE;\r\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);\r\n }\r\n else {\r\n const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);\r\n }\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n assert(pathGetLength(changePath) === 1, \"Can't have a priority with additional path components\");\r\n const oldEventNode = oldEventSnap.getNode();\r\n serverNode = viewCache.serverCache.getNode();\r\n // we might have overwrites for this priority\r\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);\r\n if (updatedPriority != null) {\r\n newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);\r\n }\r\n else {\r\n // priority didn't change, keep old node\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n // update child\r\n let newEventChild;\r\n if (oldEventSnap.isCompleteForChild(childKey)) {\r\n serverNode = viewCache.serverCache.getNode();\r\n const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);\r\n if (eventChildUpdate != null) {\r\n newEventChild = oldEventSnap\r\n .getNode()\r\n .getImmediateChild(childKey)\r\n .updateChild(childChangePath, eventChildUpdate);\r\n }\r\n else {\r\n // Nothing changed, just keep the old child\r\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n }\r\n }\r\n else {\r\n newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n }\r\n if (newEventChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\r\n }\r\n else {\r\n // no complete child available or no change\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n }\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());\r\n }\r\n}\r\nfunction viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\r\n const oldServerSnap = oldViewCache.serverCache;\r\n let newServerCache;\r\n const serverFilter = filterServerNode\r\n ? viewProcessor.filter\r\n : viewProcessor.filter.getIndexedFilter();\r\n if (pathIsEmpty(changePath)) {\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\r\n }\r\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\r\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\r\n const newServerNode = oldServerSnap\r\n .getNode()\r\n .updateChild(changePath, changedSnap);\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (!oldServerSnap.isCompleteForPath(changePath) &&\r\n pathGetLength(changePath) > 1) {\r\n // We don't update incomplete nodes with updates intended for other listeners\r\n return oldViewCache;\r\n }\r\n const childChangePath = pathPopFront(changePath);\r\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\r\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\r\n if (childKey === '.priority') {\r\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\r\n }\r\n else {\r\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);\r\n }\r\n }\r\n const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());\r\n const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);\r\n}\r\nfunction viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\r\n const oldEventSnap = oldViewCache.eventCache;\r\n let newViewCache, newEventCache;\r\n const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\r\n if (pathIsEmpty(changePath)) {\r\n newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n let newChild;\r\n if (pathIsEmpty(childChangePath)) {\r\n // Child overwrite, we can replace the child\r\n newChild = changedSnap;\r\n }\r\n else {\r\n const childNode = source.getCompleteChild(childKey);\r\n if (childNode != null) {\r\n if (pathGetBack(childChangePath) === '.priority' &&\r\n childNode.getChild(pathParent(childChangePath)).isEmpty()) {\r\n // This is a priority update on an empty node. If this node exists on the server, the\r\n // server will send down the priority in the update, so ignore for now\r\n newChild = childNode;\r\n }\r\n else {\r\n newChild = childNode.updateChild(childChangePath, changedSnap);\r\n }\r\n }\r\n else {\r\n // There is no complete child node available\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n }\r\n if (!oldChild.equals(newChild)) {\r\n const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n newViewCache = oldViewCache;\r\n }\r\n }\r\n }\r\n return newViewCache;\r\n}\r\nfunction viewProcessorCacheHasChild(viewCache, childKey) {\r\n return viewCache.eventCache.isCompleteForChild(childKey);\r\n}\r\nfunction viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorApplyMerge(viewProcessor, node, merge) {\r\n merge.foreach((relativePath, childNode) => {\r\n node = node.updateChild(relativePath, childNode);\r\n });\r\n return node;\r\n}\r\nfunction viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\r\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\r\n // wait for the complete data update coming soon.\r\n if (viewCache.serverCache.getNode().isEmpty() &&\r\n !viewCache.serverCache.isFullyInitialized()) {\r\n return viewCache;\r\n }\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n let viewMergeTree;\r\n if (pathIsEmpty(path)) {\r\n viewMergeTree = changedChildren;\r\n }\r\n else {\r\n viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);\r\n }\r\n const serverNode = viewCache.serverCache.getNode();\r\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (serverNode.hasChild(childKey)) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\r\n const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&\r\n childMergeTree.value === null;\r\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\r\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\r\n return viewCache;\r\n }\r\n // Only filter server node if it is currently filtered\r\n const filterServerNode = viewCache.serverCache.isFiltered();\r\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\r\n // now that it won't be shadowed.\r\n const serverCache = viewCache.serverCache;\r\n if (affectedTree.value != null) {\r\n // This is an overwrite.\r\n if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\r\n serverCache.isCompleteForPath(ackPath)) {\r\n return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else if (pathIsEmpty(ackPath)) {\r\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\r\n // should just re-apply whatever we have in our cache as a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\r\n changedChildren = changedChildren.set(new Path(name), node);\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else {\r\n return viewCache;\r\n }\r\n }\r\n else {\r\n // This is a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n affectedTree.foreach((mergePath, value) => {\r\n const serverCachePath = pathChild(ackPath, mergePath);\r\n if (serverCache.isCompleteForPath(serverCachePath)) {\r\n changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));\r\n }\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n}\r\nfunction viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {\r\n const oldServerNode = viewCache.serverCache;\r\n const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);\r\n}\r\nfunction viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {\r\n let complete;\r\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\r\n return viewCache;\r\n }\r\n else {\r\n const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\r\n const oldEventCache = viewCache.eventCache.getNode();\r\n let newEventCache;\r\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\r\n let newNode;\r\n if (viewCache.serverCache.isFullyInitialized()) {\r\n newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n }\r\n else {\r\n const serverChildren = viewCache.serverCache.getNode();\r\n assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');\r\n newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);\r\n }\r\n newNode = newNode;\r\n newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n if (newChild == null &&\r\n viewCache.serverCache.isCompleteForChild(childKey)) {\r\n newChild = oldEventCache.getImmediateChild(childKey);\r\n }\r\n if (newChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);\r\n }\r\n else if (viewCache.eventCache.getNode().hasChild(childKey)) {\r\n // No complete child available, delete the existing one, if any\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);\r\n }\r\n else {\r\n newEventCache = oldEventCache;\r\n }\r\n if (newEventCache.isEmpty() &&\r\n viewCache.serverCache.isFullyInitialized()) {\r\n // We might have reverted all child writes. Maybe the old event was a leaf node\r\n complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n if (complete.isLeafNode()) {\r\n newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);\r\n }\r\n }\r\n }\r\n complete =\r\n viewCache.serverCache.isFullyInitialized() ||\r\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());\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/**\r\n * A view represents a specific location and query that has 1 or more event registrations.\r\n *\r\n * It does several things:\r\n * - Maintains the list of event registrations for this location/query.\r\n * - Maintains a cache of the data visible for this location/query.\r\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\r\n * registrations returns the set of events to be raised.\r\n */\r\nclass View {\r\n constructor(query_, initialViewCache) {\r\n this.query_ = query_;\r\n this.eventRegistrations_ = [];\r\n const params = this.query_._queryParams;\r\n const indexFilter = new IndexedFilter(params.getIndex());\r\n const filter = queryParamsGetNodeFilter(params);\r\n this.processor_ = newViewProcessor(filter);\r\n const initialServerCache = initialViewCache.serverCache;\r\n const initialEventCache = initialViewCache.eventCache;\r\n // Don't filter server node with other filter than index, wait for tagged listen\r\n const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\r\n const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\r\n const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\r\n const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\r\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\r\n this.eventGenerator_ = new EventGenerator(this.query_);\r\n }\r\n get query() {\r\n return this.query_;\r\n }\r\n}\r\nfunction viewGetServerCache(view) {\r\n return view.viewCache_.serverCache.getNode();\r\n}\r\nfunction viewGetCompleteNode(view) {\r\n return viewCacheGetCompleteEventSnap(view.viewCache_);\r\n}\r\nfunction viewGetCompleteServerCache(view, path) {\r\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\r\n if (cache) {\r\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\r\n // we need to see if it contains the child we're interested in.\r\n if (view.query._queryParams.loadsAllData() ||\r\n (!pathIsEmpty(path) &&\r\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {\r\n return cache.getChild(path);\r\n }\r\n }\r\n return null;\r\n}\r\nfunction viewIsEmpty(view) {\r\n return view.eventRegistrations_.length === 0;\r\n}\r\nfunction viewAddEventRegistration(view, eventRegistration) {\r\n view.eventRegistrations_.push(eventRegistration);\r\n}\r\n/**\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction viewRemoveEventRegistration(view, eventRegistration, cancelError) {\r\n const cancelEvents = [];\r\n if (cancelError) {\r\n assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\r\n const path = view.query._path;\r\n view.eventRegistrations_.forEach(registration => {\r\n const maybeEvent = registration.createCancelEvent(cancelError, path);\r\n if (maybeEvent) {\r\n cancelEvents.push(maybeEvent);\r\n }\r\n });\r\n }\r\n if (eventRegistration) {\r\n let remaining = [];\r\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\r\n const existing = view.eventRegistrations_[i];\r\n if (!existing.matches(eventRegistration)) {\r\n remaining.push(existing);\r\n }\r\n else if (eventRegistration.hasAnyCallback()) {\r\n // We're removing just this one\r\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\r\n break;\r\n }\r\n }\r\n view.eventRegistrations_ = remaining;\r\n }\r\n else {\r\n view.eventRegistrations_ = [];\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Applies the given Operation, updates our cache, and returns the appropriate events.\r\n */\r\nfunction viewApplyOperation(view, operation, writesCache, completeServerCache) {\r\n if (operation.type === OperationType.MERGE &&\r\n operation.source.queryId !== null) {\r\n assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');\r\n assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');\r\n }\r\n const oldViewCache = view.viewCache_;\r\n const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);\r\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\r\n assert(result.viewCache.serverCache.isFullyInitialized() ||\r\n !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');\r\n view.viewCache_ = result.viewCache;\r\n return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);\r\n}\r\nfunction viewGetInitialEvents(view, registration) {\r\n const eventSnap = view.viewCache_.eventCache;\r\n const initialChanges = [];\r\n if (!eventSnap.getNode().isLeafNode()) {\r\n const eventNode = eventSnap.getNode();\r\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n initialChanges.push(changeChildAdded(key, childNode));\r\n });\r\n }\r\n if (eventSnap.isFullyInitialized()) {\r\n initialChanges.push(changeValue(eventSnap.getNode()));\r\n }\r\n return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);\r\n}\r\nfunction viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {\r\n const registrations = eventRegistration\r\n ? [eventRegistration]\r\n : view.eventRegistrations_;\r\n return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);\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\nlet referenceConstructor$1;\r\n/**\r\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\r\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\r\n * and user writes (set, transaction, update).\r\n *\r\n * It's responsible for:\r\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\r\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\r\n * applyUserOverwrite, etc.)\r\n */\r\nclass SyncPoint {\r\n constructor() {\r\n /**\r\n * The Views being tracked at this location in the tree, stored as a map where the key is a\r\n * queryId and the value is the View for that query.\r\n *\r\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\r\n */\r\n this.views = new Map();\r\n }\r\n}\r\nfunction syncPointSetReferenceConstructor(val) {\r\n assert(!referenceConstructor$1, '__referenceConstructor has already been defined');\r\n referenceConstructor$1 = val;\r\n}\r\nfunction syncPointGetReferenceConstructor() {\r\n assert(referenceConstructor$1, 'Reference.ts has not been loaded');\r\n return referenceConstructor$1;\r\n}\r\nfunction syncPointIsEmpty(syncPoint) {\r\n return syncPoint.views.size === 0;\r\n}\r\nfunction syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {\r\n const queryId = operation.source.queryId;\r\n if (queryId !== null) {\r\n const view = syncPoint.views.get(queryId);\r\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\r\n return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);\r\n }\r\n else {\r\n let events = [];\r\n for (const view of syncPoint.views.values()) {\r\n events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Get a view for the specified query.\r\n *\r\n * @param query - The query to return a view for\r\n * @param writesCache\r\n * @param serverCache\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {\r\n const queryId = query._queryIdentifier;\r\n const view = syncPoint.views.get(queryId);\r\n if (!view) {\r\n // TODO: make writesCache take flag for complete server node\r\n let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);\r\n let eventCacheComplete = false;\r\n if (eventCache) {\r\n eventCacheComplete = true;\r\n }\r\n else if (serverCache instanceof ChildrenNode) {\r\n eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);\r\n eventCacheComplete = false;\r\n }\r\n else {\r\n eventCache = ChildrenNode.EMPTY_NODE;\r\n eventCacheComplete = false;\r\n }\r\n const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));\r\n return new View(query, viewCache);\r\n }\r\n return view;\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @param query\r\n * @param eventRegistration\r\n * @param writesCache\r\n * @param serverCache - Complete server cache, if we have it.\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);\r\n if (!syncPoint.views.has(query._queryIdentifier)) {\r\n syncPoint.views.set(query._queryIdentifier, view);\r\n }\r\n // This is guaranteed to exist now, we just created anything that was missing\r\n viewAddEventRegistration(view, eventRegistration);\r\n return viewGetInitialEvents(view, eventRegistration);\r\n}\r\n/**\r\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\r\n *\r\n * If query is the default query, we'll check all views for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\r\n *\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns removed queries and any cancel events\r\n */\r\nfunction syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {\r\n const queryId = query._queryIdentifier;\r\n const removed = [];\r\n let cancelEvents = [];\r\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\r\n if (queryId === 'default') {\r\n // When you do ref.off(...), we search all views for the registration to remove.\r\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(viewQueryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // remove the callback from the specific view.\r\n const view = syncPoint.views.get(queryId);\r\n if (view) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(queryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\r\n // We removed our last complete view.\r\n removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));\r\n }\r\n return { removed, events: cancelEvents };\r\n}\r\nfunction syncPointGetQueryViews(syncPoint) {\r\n const result = [];\r\n for (const view of syncPoint.views.values()) {\r\n if (!view.query._queryParams.loadsAllData()) {\r\n result.push(view);\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * @param path - The path to the desired complete snapshot\r\n * @returns A complete cache, if it exists\r\n */\r\nfunction syncPointGetCompleteServerCache(syncPoint, path) {\r\n let serverCache = null;\r\n for (const view of syncPoint.views.values()) {\r\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\r\n }\r\n return serverCache;\r\n}\r\nfunction syncPointViewForQuery(syncPoint, query) {\r\n const params = query._queryParams;\r\n if (params.loadsAllData()) {\r\n return syncPointGetCompleteView(syncPoint);\r\n }\r\n else {\r\n const queryId = query._queryIdentifier;\r\n return syncPoint.views.get(queryId);\r\n }\r\n}\r\nfunction syncPointViewExistsForQuery(syncPoint, query) {\r\n return syncPointViewForQuery(syncPoint, query) != null;\r\n}\r\nfunction syncPointHasCompleteView(syncPoint) {\r\n return syncPointGetCompleteView(syncPoint) != null;\r\n}\r\nfunction syncPointGetCompleteView(syncPoint) {\r\n for (const view of syncPoint.views.values()) {\r\n if (view.query._queryParams.loadsAllData()) {\r\n return view;\r\n }\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\nlet referenceConstructor;\r\nfunction syncTreeSetReferenceConstructor(val) {\r\n assert(!referenceConstructor, '__referenceConstructor has already been defined');\r\n referenceConstructor = val;\r\n}\r\nfunction syncTreeGetReferenceConstructor() {\r\n assert(referenceConstructor, 'Reference.ts has not been loaded');\r\n return referenceConstructor;\r\n}\r\n/**\r\n * Static tracker for next query tag.\r\n */\r\nlet syncTreeNextQueryTag_ = 1;\r\n/**\r\n * SyncTree is the central class for managing event callback registration, data caching, views\r\n * (query processing), and event generation. There are typically two SyncTree instances for\r\n * each Repo, one for the normal Firebase data, and one for the .info data.\r\n *\r\n * It has a number of responsibilities, including:\r\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\r\n * - Applying and caching data changes for user set(), transaction(), and update() calls\r\n * (applyUserOverwrite(), applyUserMerge()).\r\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\r\n * applyServerMerge()).\r\n * - Generating user-facing events for server and user changes (all of the apply* methods\r\n * return the set of events that need to be raised as a result).\r\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\r\n * to the correct set of paths and queries to satisfy the current set of user event\r\n * callbacks (listens are started/stopped using the provided listenProvider).\r\n *\r\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\r\n * events are returned to the caller rather than raised synchronously.\r\n *\r\n */\r\nclass SyncTree {\r\n /**\r\n * @param listenProvider_ - Used by SyncTree to start / stop listening\r\n * to server data.\r\n */\r\n constructor(listenProvider_) {\r\n this.listenProvider_ = listenProvider_;\r\n /**\r\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\r\n */\r\n this.syncPointTree_ = new ImmutableTree(null);\r\n /**\r\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\r\n */\r\n this.pendingWriteTree_ = newWriteTree();\r\n this.tagToQueryMap = new Map();\r\n this.queryToTagMap = new Map();\r\n }\r\n}\r\n/**\r\n * Apply the data changes for a user-generated set() or transaction() call.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {\r\n // Record pending write.\r\n writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);\r\n if (!visible) {\r\n return [];\r\n }\r\n else {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));\r\n }\r\n}\r\n/**\r\n * Apply the data from a user-generated update() call\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {\r\n // Record pending merge.\r\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));\r\n}\r\n/**\r\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\r\n *\r\n * @param revert - True if the given write failed and needs to be reverted\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAckUserWrite(syncTree, writeId, revert = false) {\r\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\r\n const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);\r\n if (!needToReevaluate) {\r\n return [];\r\n }\r\n else {\r\n let affectedTree = new ImmutableTree(null);\r\n if (write.snap != null) {\r\n // overwrite\r\n affectedTree = affectedTree.set(newEmptyPath(), true);\r\n }\r\n else {\r\n each(write.children, (pathString) => {\r\n affectedTree = affectedTree.set(new Path(pathString), true);\r\n });\r\n }\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));\r\n }\r\n}\r\n/**\r\n * Apply new server data for the specified path..\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerOverwrite(syncTree, path, newData) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));\r\n}\r\n/**\r\n * Apply new server data to be merged in at the specified path.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerMerge(syncTree, path, changedChildren) {\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));\r\n}\r\n/**\r\n * Apply a listen complete for a query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyListenComplete(syncTree, path) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));\r\n}\r\n/**\r\n * Apply a listen complete for a tagged query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedListenComplete(syncTree, path, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Remove event callback(s).\r\n *\r\n * If query is the default query, we'll check all queries for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\r\n *\r\n * @param eventRegistration - If null, all callbacks are removed.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\r\n * deduping needs to take place. This flag allows toggling of that behavior\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {\r\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\r\n const path = query._path;\r\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\r\n let cancelEvents = [];\r\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\r\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\r\n // not loadsAllData().\r\n if (maybeSyncPoint &&\r\n (query._queryIdentifier === 'default' ||\r\n syncPointViewExistsForQuery(maybeSyncPoint, query))) {\r\n const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);\r\n if (syncPointIsEmpty(maybeSyncPoint)) {\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\r\n }\r\n const removed = removedAndEvents.removed;\r\n cancelEvents = removedAndEvents.events;\r\n if (!skipListenerDedup) {\r\n /**\r\n * We may have just removed one of many listeners and can short-circuit this whole process\r\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\r\n * properly set up.\r\n */\r\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\r\n // queryId === 'default'\r\n const removingDefault = -1 !==\r\n removed.findIndex(query => {\r\n return query._queryParams.loadsAllData();\r\n });\r\n const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));\r\n if (removingDefault && !covered) {\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\r\n // removal\r\n if (!subtree.isEmpty()) {\r\n // We need to fold over our subtree and collect the listeners to send\r\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\r\n // Ok, we've collected all the listens we need. Set them up.\r\n for (let i = 0; i < newViews.length; ++i) {\r\n const view = newViews[i], newQuery = view.query;\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);\r\n }\r\n }\r\n // Otherwise there's nothing below us, so nothing we need to start listening on\r\n }\r\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\r\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\r\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\r\n if (!covered && removed.length > 0 && !cancelError) {\r\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\r\n // default. Otherwise, we need to iterate through and cancel each individual query\r\n if (removingDefault) {\r\n // We don't tag default listeners\r\n const defaultTag = null;\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);\r\n }\r\n else {\r\n removed.forEach((queryToRemove) => {\r\n const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);\r\n });\r\n }\r\n }\r\n }\r\n // Now, clear all of the tags we're tracking for the removed listens\r\n syncTreeRemoveTags_(syncTree, removed);\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Apply new server data for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey != null) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // Query must have been removed already\r\n return [];\r\n }\r\n}\r\n/**\r\n * Apply server data to be merged in for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {\r\n const path = query._path;\r\n let serverCache = null;\r\n let foundAncestorDefaultView = false;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let serverCacheComplete;\r\n if (serverCache != null) {\r\n serverCacheComplete = true;\r\n }\r\n else {\r\n serverCacheComplete = false;\r\n serverCache = ChildrenNode.EMPTY_NODE;\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n subtree.foreachChild((childName, childSyncPoint) => {\r\n const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());\r\n if (completeCache) {\r\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\r\n }\r\n });\r\n }\r\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\r\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\r\n // We need to track a tag for this query\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');\r\n const tag = syncTreeGetNextQueryTag_();\r\n syncTree.queryToTagMap.set(queryKey, tag);\r\n syncTree.tagToQueryMap.set(tag, queryKey);\r\n }\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\r\n let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);\r\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\r\n const view = syncPointViewForQuery(syncPoint, query);\r\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\r\n }\r\n return events;\r\n}\r\n/**\r\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\r\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\r\n * have a listener above, and atomic operations would correctly show a jitter of ->\r\n * as the write is applied locally and then acknowledged at the server.\r\n *\r\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\r\n *\r\n * @param path - The path to the data we want\r\n * @param writeIdsToExclude - A specific set to be excluded\r\n */\r\nfunction syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {\r\n const includeHiddenSets = true;\r\n const writeTree = syncTree.pendingWriteTree_;\r\n const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {\r\n const relativePath = newRelativePath(pathSoFar, path);\r\n const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);\r\n if (serverCache) {\r\n return serverCache;\r\n }\r\n });\r\n return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);\r\n}\r\nfunction syncTreeGetServerValue(syncTree, query) {\r\n const path = query._path;\r\n let serverCache = null;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n const serverCacheComplete = serverCache != null;\r\n const serverCacheNode = serverCacheComplete\r\n ? new CacheNode(serverCache, true, false)\r\n : null;\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);\r\n return viewGetCompleteNode(view);\r\n}\r\n/**\r\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\r\n *\r\n * NOTES:\r\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\r\n *\r\n * - We call applyOperation() on each SyncPoint passing three things:\r\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\r\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\r\n * 3. A snapshot Node with cached server data, if we have it.\r\n *\r\n * - We concatenate all of the events returned by each SyncPoint and return the result.\r\n */\r\nfunction syncTreeApplyOperationToSyncPoints_(syncTree, operation) {\r\n return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, \r\n /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n if (pathIsEmpty(operation.path)) {\r\n return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\r\n }\r\n else {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n const childName = pathGetFront(operation.path);\r\n const childOperation = operation.operationForChild(childName);\r\n const childTree = syncPointTree.children.get(childName);\r\n if (childTree && childOperation) {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n syncPointTree.children.inorderTraversal((childName, childTree) => {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n const childOperation = operation.operationForChild(childName);\r\n if (childOperation) {\r\n events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n });\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n}\r\nfunction syncTreeCreateListenerForView_(syncTree, view) {\r\n const query = view.query;\r\n const tag = syncTreeTagForQuery(syncTree, query);\r\n return {\r\n hashFn: () => {\r\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\r\n return cache.hash();\r\n },\r\n onComplete: (status) => {\r\n if (status === 'ok') {\r\n if (tag) {\r\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\r\n }\r\n else {\r\n return syncTreeApplyListenComplete(syncTree, query._path);\r\n }\r\n }\r\n else {\r\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\r\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\r\n const error = errorForServerCode(status, query);\r\n return syncTreeRemoveEventRegistration(syncTree, query, \r\n /*eventRegistration*/ null, error);\r\n }\r\n }\r\n };\r\n}\r\n/**\r\n * Return the tag associated with the given query.\r\n */\r\nfunction syncTreeTagForQuery(syncTree, query) {\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n return syncTree.queryToTagMap.get(queryKey);\r\n}\r\n/**\r\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\r\n */\r\nfunction syncTreeMakeQueryKey_(query) {\r\n return query._path.toString() + '$' + query._queryIdentifier;\r\n}\r\n/**\r\n * Return the query associated with the given tag, if we have one\r\n */\r\nfunction syncTreeQueryKeyForTag_(syncTree, tag) {\r\n return syncTree.tagToQueryMap.get(tag);\r\n}\r\n/**\r\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\r\n */\r\nfunction syncTreeParseQueryKey_(queryKey) {\r\n const splitIndex = queryKey.indexOf('$');\r\n assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\r\n return {\r\n queryId: queryKey.substr(splitIndex + 1),\r\n path: new Path(queryKey.substr(0, splitIndex))\r\n };\r\n}\r\n/**\r\n * A helper method to apply tagged operations\r\n */\r\nfunction syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {\r\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\r\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);\r\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\r\n}\r\n/**\r\n * This collapses multiple unfiltered views into a single view, since we only need a single\r\n * listener for them.\r\n */\r\nfunction syncTreeCollectDistinctViewsForSubTree_(subtree) {\r\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\r\n return [completeView];\r\n }\r\n else {\r\n // No complete view here, flatten any deeper listens into an array\r\n let views = [];\r\n if (maybeChildSyncPoint) {\r\n views = syncPointGetQueryViews(maybeChildSyncPoint);\r\n }\r\n each(childMap, (_key, childViews) => {\r\n views = views.concat(childViews);\r\n });\r\n return views;\r\n }\r\n });\r\n}\r\n/**\r\n * Normalizes a query to a query we send the server for listening\r\n *\r\n * @returns The normalized query\r\n */\r\nfunction syncTreeQueryForListening_(query) {\r\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\r\n // We treat queries that load all data as default queries\r\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\r\n // from Query\r\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\r\n }\r\n else {\r\n return query;\r\n }\r\n}\r\nfunction syncTreeRemoveTags_(syncTree, queries) {\r\n for (let j = 0; j < queries.length; ++j) {\r\n const removedQuery = queries[j];\r\n if (!removedQuery._queryParams.loadsAllData()) {\r\n // We should have a tag for this\r\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\r\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\r\n syncTree.queryToTagMap.delete(removedQueryKey);\r\n syncTree.tagToQueryMap.delete(removedQueryTag);\r\n }\r\n }\r\n}\r\n/**\r\n * Static accessor for query tags.\r\n */\r\nfunction syncTreeGetNextQueryTag_() {\r\n return syncTreeNextQueryTag_++;\r\n}\r\n/**\r\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\r\n *\r\n * @returns This method can return events to support synchronous data sources\r\n */\r\nfunction syncTreeSetupListener_(syncTree, query, view) {\r\n const path = query._path;\r\n const tag = syncTreeTagForQuery(syncTree, query);\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\r\n // may need to shadow other listens as well.\r\n if (tag) {\r\n assert(!syncPointHasCompleteView(subtree.value), \"If we're adding a query, it shouldn't be shadowed\");\r\n }\r\n else {\r\n // Shadow everything at or below this location, this is a default listener.\r\n const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (!pathIsEmpty(relativePath) &&\r\n maybeChildSyncPoint &&\r\n syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\r\n }\r\n else {\r\n // No default listener here, flatten any deeper queries into an array\r\n let queries = [];\r\n if (maybeChildSyncPoint) {\r\n queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));\r\n }\r\n each(childMap, (_key, childQueries) => {\r\n queries = queries.concat(childQueries);\r\n });\r\n return queries;\r\n }\r\n });\r\n for (let i = 0; i < queriesToStop.length; ++i) {\r\n const queryToStop = queriesToStop[i];\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));\r\n }\r\n }\r\n return events;\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\nclass ExistingValueProvider {\r\n constructor(node_) {\r\n this.node_ = node_;\r\n }\r\n getImmediateChild(childName) {\r\n const child = this.node_.getImmediateChild(childName);\r\n return new ExistingValueProvider(child);\r\n }\r\n node() {\r\n return this.node_;\r\n }\r\n}\r\nclass DeferredValueProvider {\r\n constructor(syncTree, path) {\r\n this.syncTree_ = syncTree;\r\n this.path_ = path;\r\n }\r\n getImmediateChild(childName) {\r\n const childPath = pathChild(this.path_, childName);\r\n return new DeferredValueProvider(this.syncTree_, childPath);\r\n }\r\n node() {\r\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\r\n }\r\n}\r\n/**\r\n * Generate placeholders for deferred values.\r\n */\r\nconst generateWithValues = function (values) {\r\n values = values || {};\r\n values['timestamp'] = values['timestamp'] || new Date().getTime();\r\n return values;\r\n};\r\n/**\r\n * Value to use when firing local events. When writing server values, fire\r\n * local events with an approximate value, otherwise return value as-is.\r\n */\r\nconst resolveDeferredLeafValue = function (value, existingVal, serverValues) {\r\n if (!value || typeof value !== 'object') {\r\n return value;\r\n }\r\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\r\n if (typeof value['.sv'] === 'string') {\r\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\r\n }\r\n else if (typeof value['.sv'] === 'object') {\r\n return resolveComplexDeferredValue(value['.sv'], existingVal);\r\n }\r\n else {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\r\n }\r\n};\r\nconst resolveScalarDeferredValue = function (op, existing, serverValues) {\r\n switch (op) {\r\n case 'timestamp':\r\n return serverValues['timestamp'];\r\n default:\r\n assert(false, 'Unexpected server value: ' + op);\r\n }\r\n};\r\nconst resolveComplexDeferredValue = function (op, existing, unused) {\r\n if (!op.hasOwnProperty('increment')) {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\r\n }\r\n const delta = op['increment'];\r\n if (typeof delta !== 'number') {\r\n assert(false, 'Unexpected increment value: ' + delta);\r\n }\r\n const existingNode = existing.node();\r\n assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');\r\n // Incrementing a non-number sets the value to the incremented amount\r\n if (!existingNode.isLeafNode()) {\r\n return delta;\r\n }\r\n const leaf = existingNode;\r\n const existingVal = leaf.getValue();\r\n if (typeof existingVal !== 'number') {\r\n return delta;\r\n }\r\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\r\n return existingVal + delta;\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the tree with the\r\n * specified generated replacement values.\r\n * @param path - path to which write is relative\r\n * @param node - new data written at path\r\n * @param syncTree - current data\r\n */\r\nconst resolveDeferredValueTree = function (path, node, syncTree, serverValues) {\r\n return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the node with the\r\n * specified generated replacement values. If there are no server values in the node,\r\n * it'll be returned as-is.\r\n */\r\nconst resolveDeferredValueSnapshot = function (node, existing, serverValues) {\r\n return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);\r\n};\r\nfunction resolveDeferredValue(node, existingVal, serverValues) {\r\n const rawPri = node.getPriority().val();\r\n const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);\r\n let newNode;\r\n if (node.isLeafNode()) {\r\n const leafNode = node;\r\n const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);\r\n if (value !== leafNode.getValue() ||\r\n priority !== leafNode.getPriority().val()) {\r\n return new LeafNode(value, nodeFromJSON(priority));\r\n }\r\n else {\r\n return node;\r\n }\r\n }\r\n else {\r\n const childrenNode = node;\r\n newNode = childrenNode;\r\n if (priority !== childrenNode.getPriority().val()) {\r\n newNode = newNode.updatePriority(new LeafNode(priority));\r\n }\r\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);\r\n if (newChildNode !== childNode) {\r\n newNode = newNode.updateImmediateChild(childName, newChildNode);\r\n }\r\n });\r\n return newNode;\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/**\r\n * A light-weight tree, traversable by path. Nodes can have both values and children.\r\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\r\n * children.\r\n */\r\nclass Tree {\r\n /**\r\n * @param name - Optional name of the node.\r\n * @param parent - Optional parent node.\r\n * @param node - Optional node to wrap.\r\n */\r\n constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {\r\n this.name = name;\r\n this.parent = parent;\r\n this.node = node;\r\n }\r\n}\r\n/**\r\n * Returns a sub-Tree for the given path.\r\n *\r\n * @param pathObj - Path to look up.\r\n * @returns Tree for path.\r\n */\r\nfunction treeSubTree(tree, pathObj) {\r\n // TODO: Require pathObj to be Path?\r\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\r\n let child = tree, next = pathGetFront(path);\r\n while (next !== null) {\r\n const childNode = safeGet(child.node.children, next) || {\r\n children: {},\r\n childCount: 0\r\n };\r\n child = new Tree(next, child, childNode);\r\n path = pathPopFront(path);\r\n next = pathGetFront(path);\r\n }\r\n return child;\r\n}\r\n/**\r\n * Returns the data associated with this tree node.\r\n *\r\n * @returns The data or null if no data exists.\r\n */\r\nfunction treeGetValue(tree) {\r\n return tree.node.value;\r\n}\r\n/**\r\n * Sets data to this tree node.\r\n *\r\n * @param value - Value to set.\r\n */\r\nfunction treeSetValue(tree, value) {\r\n tree.node.value = value;\r\n treeUpdateParents(tree);\r\n}\r\n/**\r\n * @returns Whether the tree has any children.\r\n */\r\nfunction treeHasChildren(tree) {\r\n return tree.node.childCount > 0;\r\n}\r\n/**\r\n * @returns Whether the tree is empty (no value or children).\r\n */\r\nfunction treeIsEmpty(tree) {\r\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\r\n}\r\n/**\r\n * Calls action for each child of this tree node.\r\n *\r\n * @param action - Action to be called for each child.\r\n */\r\nfunction treeForEachChild(tree, action) {\r\n each(tree.node.children, (child, childTree) => {\r\n action(new Tree(child, tree, childTree));\r\n });\r\n}\r\n/**\r\n * Does a depth-first traversal of this node's descendants, calling action for each one.\r\n *\r\n * @param action - Action to be called for each child.\r\n * @param includeSelf - Whether to call action on this node as well. Defaults to\r\n * false.\r\n * @param childrenFirst - Whether to call action on children before calling it on\r\n * parent.\r\n */\r\nfunction treeForEachDescendant(tree, action, includeSelf, childrenFirst) {\r\n if (includeSelf && !childrenFirst) {\r\n action(tree);\r\n }\r\n treeForEachChild(tree, child => {\r\n treeForEachDescendant(child, action, true, childrenFirst);\r\n });\r\n if (includeSelf && childrenFirst) {\r\n action(tree);\r\n }\r\n}\r\n/**\r\n * Calls action on each ancestor node.\r\n *\r\n * @param action - Action to be called on each parent; return\r\n * true to abort.\r\n * @param includeSelf - Whether to call action on this node as well.\r\n * @returns true if the action callback returned true.\r\n */\r\nfunction treeForEachAncestor(tree, action, includeSelf) {\r\n let node = includeSelf ? tree : tree.parent;\r\n while (node !== null) {\r\n if (action(node)) {\r\n return true;\r\n }\r\n node = node.parent;\r\n }\r\n return false;\r\n}\r\n/**\r\n * @returns The path of this tree node, as a Path.\r\n */\r\nfunction treeGetPath(tree) {\r\n return new Path(tree.parent === null\r\n ? tree.name\r\n : treeGetPath(tree.parent) + '/' + tree.name);\r\n}\r\n/**\r\n * Adds or removes this child from its parent based on whether it's empty or not.\r\n */\r\nfunction treeUpdateParents(tree) {\r\n if (tree.parent !== null) {\r\n treeUpdateChild(tree.parent, tree.name, tree);\r\n }\r\n}\r\n/**\r\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\r\n *\r\n * @param childName - The name of the child to update.\r\n * @param child - The child to update.\r\n */\r\nfunction treeUpdateChild(tree, childName, child) {\r\n const childEmpty = treeIsEmpty(child);\r\n const childExists = contains(tree.node.children, childName);\r\n if (childEmpty && childExists) {\r\n delete tree.node.children[childName];\r\n tree.node.childCount--;\r\n treeUpdateParents(tree);\r\n }\r\n else if (!childEmpty && !childExists) {\r\n tree.node.children[childName] = child.node;\r\n tree.node.childCount++;\r\n treeUpdateParents(tree);\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/**\r\n * True for invalid Firebase keys\r\n */\r\nconst INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * True for invalid Firebase paths.\r\n * Allows '/' in paths.\r\n */\r\nconst INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * Maximum number of characters to allow in leaf value\r\n */\r\nconst MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\r\nconst isValidKey = function (key) {\r\n return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));\r\n};\r\nconst isValidPathString = function (pathString) {\r\n return (typeof pathString === 'string' &&\r\n pathString.length !== 0 &&\r\n !INVALID_PATH_REGEX_.test(pathString));\r\n};\r\nconst isValidRootPathString = function (pathString) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n return isValidPathString(pathString);\r\n};\r\nconst isValidPriority = function (priority) {\r\n return (priority === null ||\r\n typeof priority === 'string' ||\r\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\r\n (priority &&\r\n typeof priority === 'object' &&\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n contains(priority, '.sv')));\r\n};\r\n/**\r\n * Pre-validate a datum passed as an argument to Firebase function.\r\n */\r\nconst validateFirebaseDataArg = function (fnName, value, path, optional) {\r\n if (optional && value === undefined) {\r\n return;\r\n }\r\n validateFirebaseData(errorPrefix(fnName, 'value'), value, path);\r\n};\r\n/**\r\n * Validate a data object client-side before sending to server.\r\n */\r\nconst validateFirebaseData = function (errorPrefix, data, path_) {\r\n const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\r\n if (data === undefined) {\r\n throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));\r\n }\r\n if (typeof data === 'function') {\r\n throw new Error(errorPrefix +\r\n 'contains a function ' +\r\n validationPathToErrorString(path) +\r\n ' with contents = ' +\r\n data.toString());\r\n }\r\n if (isInvalidJSONNumber(data)) {\r\n throw new Error(errorPrefix +\r\n 'contains ' +\r\n data.toString() +\r\n ' ' +\r\n validationPathToErrorString(path));\r\n }\r\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\r\n if (typeof data === 'string' &&\r\n data.length > MAX_LEAF_SIZE_ / 3 &&\r\n stringLength(data) > MAX_LEAF_SIZE_) {\r\n throw new Error(errorPrefix +\r\n 'contains a string greater than ' +\r\n MAX_LEAF_SIZE_ +\r\n ' utf8 bytes ' +\r\n validationPathToErrorString(path) +\r\n \" ('\" +\r\n data.substring(0, 50) +\r\n \"...')\");\r\n }\r\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\r\n // to save extra walking of large objects.\r\n if (data && typeof data === 'object') {\r\n let hasDotValue = false;\r\n let hasActualChild = false;\r\n each(data, (key, value) => {\r\n if (key === '.value') {\r\n hasDotValue = true;\r\n }\r\n else if (key !== '.priority' && key !== '.sv') {\r\n hasActualChild = true;\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix +\r\n ' contains an invalid key (' +\r\n key +\r\n ') ' +\r\n validationPathToErrorString(path) +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n validationPathPush(path, key);\r\n validateFirebaseData(errorPrefix, value, path);\r\n validationPathPop(path);\r\n });\r\n if (hasDotValue && hasActualChild) {\r\n throw new Error(errorPrefix +\r\n ' contains \".value\" child ' +\r\n validationPathToErrorString(path) +\r\n ' in addition to actual children.');\r\n }\r\n }\r\n};\r\n/**\r\n * Pre-validate paths passed in the firebase function.\r\n */\r\nconst validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\r\n let i, curPath;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n const keys = pathSlice(curPath);\r\n for (let j = 0; j < keys.length; j++) {\r\n if (keys[j] === '.priority' && j === keys.length - 1) ;\r\n else if (!isValidKey(keys[j])) {\r\n throw new Error(errorPrefix +\r\n 'contains an invalid key (' +\r\n keys[j] +\r\n ') in path ' +\r\n curPath.toString() +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n }\r\n // Check that update keys are not descendants of each other.\r\n // We rely on the property that sorting guarantees that ancestors come\r\n // right before descendants.\r\n mergePaths.sort(pathCompare);\r\n let prevPath = null;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n if (prevPath !== null && pathContains(prevPath, curPath)) {\r\n throw new Error(errorPrefix +\r\n 'contains a path ' +\r\n prevPath.toString() +\r\n ' that is ancestor of another path ' +\r\n curPath.toString());\r\n }\r\n prevPath = curPath;\r\n }\r\n};\r\n/**\r\n * pre-validate an object passed as an argument to firebase function (\r\n * must be an object - e.g. for firebase.update()).\r\n */\r\nconst validateFirebaseMergeDataArg = function (fnName, data, path, optional) {\r\n if (optional && data === undefined) {\r\n return;\r\n }\r\n const errorPrefix$1 = errorPrefix(fnName, 'values');\r\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\r\n throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');\r\n }\r\n const mergePaths = [];\r\n each(data, (key, value) => {\r\n const curPath = new Path(key);\r\n validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));\r\n if (pathGetBack(curPath) === '.priority') {\r\n if (!isValidPriority(value)) {\r\n throw new Error(errorPrefix$1 +\r\n \"contains an invalid value for '\" +\r\n curPath.toString() +\r\n \"', which must be a valid \" +\r\n 'Firebase priority (a string, finite number, server value, or null).');\r\n }\r\n }\r\n mergePaths.push(curPath);\r\n });\r\n validateFirebaseMergePaths(errorPrefix$1, mergePaths);\r\n};\r\nconst validatePriority = function (fnName, priority, optional) {\r\n if (optional && priority === undefined) {\r\n return;\r\n }\r\n if (isInvalidJSONNumber(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'is ' +\r\n priority.toString() +\r\n ', but must be a valid Firebase priority (a string, finite number, ' +\r\n 'server value, or null).');\r\n }\r\n // Special case to allow importing data with a .sv.\r\n if (!isValidPriority(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'must be a valid Firebase priority ' +\r\n '(a string, finite number, server value, or null).');\r\n }\r\n};\r\nconst validateKey = function (fnName, argumentName, key, optional) {\r\n if (optional && key === undefined) {\r\n return;\r\n }\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid key = \"' +\r\n key +\r\n '\". Firebase keys must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\r\n }\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validatePathString = function (fnName, argumentName, pathString, optional) {\r\n if (optional && pathString === undefined) {\r\n return;\r\n }\r\n if (!isValidPathString(pathString)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid path = \"' +\r\n pathString +\r\n '\". Paths must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\r\n }\r\n};\r\nconst validateRootPathString = function (fnName, argumentName, pathString, optional) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n validatePathString(fnName, argumentName, pathString, optional);\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validateWritablePath = function (fnName, path) {\r\n if (pathGetFront(path) === '.info') {\r\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\r\n }\r\n};\r\nconst validateUrl = function (fnName, parsedUrl) {\r\n // TODO = Validate server better.\r\n const pathString = parsedUrl.path.toString();\r\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\r\n parsedUrl.repoInfo.host.length === 0 ||\r\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\r\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\r\n (pathString.length !== 0 && !isValidRootPathString(pathString))) {\r\n throw new Error(errorPrefix(fnName, 'url') +\r\n 'must be a valid firebase URL and ' +\r\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\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/**\r\n * The event queue serves a few purposes:\r\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\r\n * events being queued.\r\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\r\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\r\n * left off, ensuring that the events are still raised synchronously and in order.\r\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\r\n * events are raised synchronously.\r\n *\r\n * NOTE: This can all go away if/when we move to async events.\r\n *\r\n */\r\nclass EventQueue {\r\n constructor() {\r\n this.eventLists_ = [];\r\n /**\r\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\r\n */\r\n this.recursionDepth_ = 0;\r\n }\r\n}\r\n/**\r\n * @param eventDataList - The new events to queue.\r\n */\r\nfunction eventQueueQueueEvents(eventQueue, eventDataList) {\r\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\r\n let currList = null;\r\n for (let i = 0; i < eventDataList.length; i++) {\r\n const data = eventDataList[i];\r\n const path = data.getPath();\r\n if (currList !== null && !pathEquals(path, currList.path)) {\r\n eventQueue.eventLists_.push(currList);\r\n currList = null;\r\n }\r\n if (currList === null) {\r\n currList = { events: [], path };\r\n }\r\n currList.events.push(data);\r\n }\r\n if (currList) {\r\n eventQueue.eventLists_.push(currList);\r\n }\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones)\r\n * for the specified path.\r\n *\r\n * It is assumed that the new events are all for the specified path.\r\n *\r\n * @param path - The path to raise events for.\r\n * @param eventDataList - The new events to raise.\r\n */\r\nfunction eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\r\n * locations related to the specified change path (i.e. all ancestors and descendants).\r\n *\r\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\r\n *\r\n * @param changedPath - The path to raise events for.\r\n * @param eventDataList - The events to raise\r\n */\r\nfunction eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||\r\n pathContains(changedPath, eventPath));\r\n}\r\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {\r\n eventQueue.recursionDepth_++;\r\n let sentAll = true;\r\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\r\n const eventList = eventQueue.eventLists_[i];\r\n if (eventList) {\r\n const eventPath = eventList.path;\r\n if (predicate(eventPath)) {\r\n eventListRaise(eventQueue.eventLists_[i]);\r\n eventQueue.eventLists_[i] = null;\r\n }\r\n else {\r\n sentAll = false;\r\n }\r\n }\r\n }\r\n if (sentAll) {\r\n eventQueue.eventLists_ = [];\r\n }\r\n eventQueue.recursionDepth_--;\r\n}\r\n/**\r\n * Iterates through the list and raises each event\r\n */\r\nfunction eventListRaise(eventList) {\r\n for (let i = 0; i < eventList.events.length; i++) {\r\n const eventData = eventList.events[i];\r\n if (eventData !== null) {\r\n eventList.events[i] = null;\r\n const eventFn = eventData.getEventRunner();\r\n if (logger) {\r\n log('event: ' + eventData.toString());\r\n }\r\n exceptionGuard(eventFn);\r\n }\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\nconst INTERRUPT_REASON = 'repo_interrupt';\r\n/**\r\n * If a transaction does not succeed after 25 retries, we abort it. Among other\r\n * things this ensure that if there's ever a bug causing a mismatch between\r\n * client / server hashes for some data, we won't retry indefinitely.\r\n */\r\nconst MAX_TRANSACTION_RETRIES = 25;\r\n/**\r\n * A connection to a single data repository.\r\n */\r\nclass Repo {\r\n constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {\r\n this.repoInfo_ = repoInfo_;\r\n this.forceRestClient_ = forceRestClient_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckProvider_ = appCheckProvider_;\r\n this.dataUpdateCount = 0;\r\n this.statsListener_ = null;\r\n this.eventQueue_ = new EventQueue();\r\n this.nextWriteId_ = 1;\r\n this.interceptServerDataCallback_ = null;\r\n /** A list of data pieces and paths to be set when this client disconnects. */\r\n this.onDisconnect_ = newSparseSnapshotTree();\r\n /** Stores queues of outstanding transactions for Firebase locations. */\r\n this.transactionQueueTree_ = new Tree();\r\n // TODO: This should be @private but it's used by test_access.js and internal.js\r\n this.persistentConnection_ = null;\r\n // This key is intentionally not updated if RepoInfo is later changed or replaced\r\n this.key = this.repoInfo_.toURLString();\r\n }\r\n /**\r\n * @returns The URL corresponding to the root of this Firebase.\r\n */\r\n toString() {\r\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\r\n }\r\n}\r\nfunction repoStart(repo, appId, authOverride) {\r\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\r\n if (repo.forceRestClient_ || beingCrawled()) {\r\n repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_);\r\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\r\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\r\n }\r\n else {\r\n // Validate authOverride\r\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\r\n if (typeof authOverride !== 'object') {\r\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\r\n }\r\n try {\r\n stringify(authOverride);\r\n }\r\n catch (e) {\r\n throw new Error('Invalid authOverride provided: ' + e);\r\n }\r\n }\r\n repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, (connectStatus) => {\r\n repoOnConnectStatus(repo, connectStatus);\r\n }, (updates) => {\r\n repoOnServerInfoUpdate(repo, updates);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);\r\n repo.server_ = repo.persistentConnection_;\r\n }\r\n repo.authTokenProvider_.addTokenChangeListener(token => {\r\n repo.server_.refreshAuthToken(token);\r\n });\r\n repo.appCheckProvider_.addTokenChangeListener(result => {\r\n repo.server_.refreshAppCheckToken(result.token);\r\n });\r\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\r\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\r\n repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));\r\n // Used for .info.\r\n repo.infoData_ = new SnapshotHolder();\r\n repo.infoSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n let infoEvents = [];\r\n const node = repo.infoData_.getNode(query._path);\r\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\r\n // on initial data...\r\n if (!node.isEmpty()) {\r\n infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);\r\n setTimeout(() => {\r\n onComplete('ok');\r\n }, 0);\r\n }\r\n return infoEvents;\r\n },\r\n stopListening: () => { }\r\n });\r\n repoUpdateInfo(repo, 'connected', false);\r\n repo.serverSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\r\n const events = onComplete(status, data);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\r\n });\r\n // No synchronous events for network-backed sync trees\r\n return [];\r\n },\r\n stopListening: (query, tag) => {\r\n repo.server_.unlisten(query, tag);\r\n }\r\n });\r\n}\r\n/**\r\n * @returns The time in milliseconds, taking the server offset into account if we have one.\r\n */\r\nfunction repoServerTime(repo) {\r\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\r\n const offset = offsetNode.val() || 0;\r\n return new Date().getTime() + offset;\r\n}\r\n/**\r\n * Generate ServerValues using some variables from the repo object.\r\n */\r\nfunction repoGenerateServerValues(repo) {\r\n return generateWithValues({\r\n timestamp: repoServerTime(repo)\r\n });\r\n}\r\n/**\r\n * Called by realtime when we get new messages from the server.\r\n */\r\nfunction repoOnDataUpdate(repo, pathString, data, isMerge, tag) {\r\n // For testing.\r\n repo.dataUpdateCount++;\r\n const path = new Path(pathString);\r\n data = repo.interceptServerDataCallback_\r\n ? repo.interceptServerDataCallback_(pathString, data)\r\n : data;\r\n let events = [];\r\n if (tag) {\r\n if (isMerge) {\r\n const taggedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);\r\n }\r\n else {\r\n const taggedSnap = nodeFromJSON(data);\r\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);\r\n }\r\n }\r\n else if (isMerge) {\r\n const changedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);\r\n }\r\n else {\r\n const snap = nodeFromJSON(data);\r\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\r\n }\r\n let affectedPath = path;\r\n if (events.length > 0) {\r\n // Since we have a listener outstanding for each transaction, receiving any events\r\n // is a proxy for some change having occurred.\r\n affectedPath = repoRerunTransactions(repo, path);\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\r\n}\r\nfunction repoOnConnectStatus(repo, connectStatus) {\r\n repoUpdateInfo(repo, 'connected', connectStatus);\r\n if (connectStatus === false) {\r\n repoRunOnDisconnectEvents(repo);\r\n }\r\n}\r\nfunction repoOnServerInfoUpdate(repo, updates) {\r\n each(updates, (key, value) => {\r\n repoUpdateInfo(repo, key, value);\r\n });\r\n}\r\nfunction repoUpdateInfo(repo, pathString, value) {\r\n const path = new Path('/.info/' + pathString);\r\n const newNode = nodeFromJSON(value);\r\n repo.infoData_.updateSnapshot(path, newNode);\r\n const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n}\r\nfunction repoGetNextWriteId(repo) {\r\n return repo.nextWriteId_++;\r\n}\r\n/**\r\n * The purpose of `getValue` is to return the latest known value\r\n * satisfying `query`.\r\n *\r\n * This method will first check for in-memory cached values\r\n * belonging to active listeners. If they are found, such values\r\n * are considered to be the most up-to-date.\r\n *\r\n * If the client is not connected, this method will wait until the\r\n * repo has established a connection and then request the value for `query`.\r\n * If the client is not able to retrieve the query result for another reason,\r\n * it reports an error.\r\n *\r\n * @param query - The query to surface a value for.\r\n */\r\nfunction repoGetValue(repo, query, eventRegistration) {\r\n // Only active queries are cached. There is no persisted cache.\r\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\r\n if (cached != null) {\r\n return Promise.resolve(cached);\r\n }\r\n return repo.server_.get(query).then(payload => {\r\n const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());\r\n /**\r\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\r\n * Add an event registration,\r\n * Update data at the path,\r\n * Raise any events,\r\n * Cleanup the SyncTree\r\n */\r\n syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);\r\n let events;\r\n if (query._queryParams.loadsAllData()) {\r\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);\r\n }\r\n else {\r\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\r\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);\r\n }\r\n /*\r\n * We need to raise events in the scenario where `get()` is called at a parent path, and\r\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\r\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\r\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\r\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\r\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\r\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\r\n * ensure the corresponding child events will get fired.\r\n */\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\r\n syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);\r\n return node;\r\n }, err => {\r\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\r\n return Promise.reject(new Error(err));\r\n });\r\n}\r\nfunction repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {\r\n repoLog(repo, 'set', {\r\n path: path.toString(),\r\n value: newVal,\r\n priority: newPriority\r\n });\r\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\r\n // (b) store unresolved paths on JSON parse\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\r\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('set at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\r\n}\r\nfunction repoUpdate(repo, path, childrenToMerge, onComplete) {\r\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\r\n // Start with our existing data and merge each child into it.\r\n let empty = true;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const changedChildren = {};\r\n each(childrenToMerge, (changedKey, changedValue) => {\r\n empty = false;\r\n changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);\r\n });\r\n if (!empty) {\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('update at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n each(childrenToMerge, (changedPath) => {\r\n const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\r\n }\r\n else {\r\n log(\"update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n }\r\n}\r\n/**\r\n * Applies all of the changes stored up in the onDisconnect_ tree.\r\n */\r\nfunction repoRunOnDisconnectEvents(repo) {\r\n repoLog(repo, 'onDisconnectEvents');\r\n const serverValues = repoGenerateServerValues(repo);\r\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\r\n sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {\r\n const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);\r\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\r\n });\r\n let events = [];\r\n sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {\r\n events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n repo.onDisconnect_ = newSparseSnapshotTree();\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\r\n}\r\nfunction repoOnDisconnectCancel(repo, path, onComplete) {\r\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSet(repo, path, value, onComplete) {\r\n const newNode = nodeFromJSON(value);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {\r\n const newNode = nodeFromJSON(value, priority);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {\r\n if (isEmpty(childrenToMerge)) {\r\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n return;\r\n }\r\n repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n if (status === 'ok') {\r\n each(childrenToMerge, (childName, childNode) => {\r\n const newChildNode = nodeFromJSON(childNode);\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);\r\n });\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoAddEventCallbackForQuery(repo, query, eventRegistration) {\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {\r\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\r\n // a little bit by handling the return values anyways.\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoInterrupt(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoResume(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.resume(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoLog(repo, ...varArgs) {\r\n let prefix = '';\r\n if (repo.persistentConnection_) {\r\n prefix = repo.persistentConnection_.id + ':';\r\n }\r\n log(prefix, ...varArgs);\r\n}\r\nfunction repoCallOnCompleteCallback(repo, callback, status, errorReason) {\r\n if (callback) {\r\n exceptionGuard(() => {\r\n if (status === 'ok') {\r\n callback(null);\r\n }\r\n else {\r\n const code = (status || 'error').toUpperCase();\r\n let message = code;\r\n if (errorReason) {\r\n message += ': ' + errorReason;\r\n }\r\n const error = new Error(message);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n error.code = code;\r\n callback(error);\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Creates a new transaction, adds it to the transactions we're tracking, and\r\n * sends it to the server if possible.\r\n *\r\n * @param path - Path at which to do transaction.\r\n * @param transactionUpdate - Update callback.\r\n * @param onComplete - Completion callback.\r\n * @param unwatcher - Function that will be called when the transaction no longer\r\n * need data updates for `path`.\r\n * @param applyLocally - Whether or not to make intermediate results visible\r\n */\r\nfunction repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {\r\n repoLog(repo, 'transaction on ' + path);\r\n // Initialize transaction.\r\n const transaction = {\r\n path,\r\n update: transactionUpdate,\r\n onComplete,\r\n // One of TransactionStatus enums.\r\n status: null,\r\n // Used when combining transactions at different locations to figure out\r\n // which one goes first.\r\n order: LUIDGenerator(),\r\n // Whether to raise local events for this transaction.\r\n applyLocally,\r\n // Count of how many times we've retried the transaction.\r\n retryCount: 0,\r\n // Function to call to clean up our .on() listener.\r\n unwatcher,\r\n // Stores why a transaction was aborted.\r\n abortReason: null,\r\n currentWriteId: null,\r\n currentInputSnapshot: null,\r\n currentOutputSnapshotRaw: null,\r\n currentOutputSnapshotResolved: null\r\n };\r\n // Run transaction initially.\r\n const currentState = repoGetLatestState(repo, path, undefined);\r\n transaction.currentInputSnapshot = currentState;\r\n const newVal = transaction.update(currentState.val());\r\n if (newVal === undefined) {\r\n // Abort transaction.\r\n transaction.unwatcher();\r\n transaction.currentOutputSnapshotRaw = null;\r\n transaction.currentOutputSnapshotResolved = null;\r\n if (transaction.onComplete) {\r\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\r\n }\r\n }\r\n else {\r\n validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\r\n // Mark as run and add to our queue.\r\n transaction.status = 0 /* TransactionStatus.RUN */;\r\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\r\n const nodeQueue = treeGetValue(queueNode) || [];\r\n nodeQueue.push(transaction);\r\n treeSetValue(queueNode, nodeQueue);\r\n // Update visibleData and raise events\r\n // Note: We intentionally raise events after updating all of our\r\n // transaction state, since the user could start new transactions from the\r\n // event callbacks.\r\n let priorityForNode;\r\n if (typeof newVal === 'object' &&\r\n newVal !== null &&\r\n contains(newVal, '.priority')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n priorityForNode = safeGet(newVal, '.priority');\r\n assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\r\n 'Priority must be a valid string, finite number, server value, or null.');\r\n }\r\n else {\r\n const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\r\n ChildrenNode.EMPTY_NODE;\r\n priorityForNode = currentNode.getPriority().val();\r\n }\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);\r\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\r\n transaction.currentOutputSnapshotResolved = newNode;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n }\r\n}\r\n/**\r\n * @param excludeSets - A specific set to exclude\r\n */\r\nfunction repoGetLatestState(repo, path, excludeSets) {\r\n return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\r\n ChildrenNode.EMPTY_NODE);\r\n}\r\n/**\r\n * Sends any already-run transactions that aren't waiting for outstanding\r\n * transactions to complete.\r\n *\r\n * Externally it's called with no arguments, but it calls itself recursively\r\n * with a particular transactionQueueTree node to recurse through the tree.\r\n *\r\n * @param node - transactionQueueTree node to start at.\r\n */\r\nfunction repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {\r\n // Before recursing, make sure any completed transactions are removed.\r\n if (!node) {\r\n repoPruneCompletedTransactionsBelowNode(repo, node);\r\n }\r\n if (treeGetValue(node)) {\r\n const queue = repoBuildTransactionQueue(repo, node);\r\n assert(queue.length > 0, 'Sending zero length transaction queue');\r\n const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);\r\n // If they're all run (and not sent), we can send them. Else, we must wait.\r\n if (allRun) {\r\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\r\n }\r\n }\r\n else if (treeHasChildren(node)) {\r\n treeForEachChild(node, childNode => {\r\n repoSendReadyTransactions(repo, childNode);\r\n });\r\n }\r\n}\r\n/**\r\n * Given a list of run transactions, send them to the server and then handle\r\n * the result (success or failure).\r\n *\r\n * @param path - The location of the queue.\r\n * @param queue - Queue of transactions under the specified location.\r\n */\r\nfunction repoSendTransactionQueue(repo, path, queue) {\r\n // Mark transactions as sent and increment retry count!\r\n const setsToIgnore = queue.map(txn => {\r\n return txn.currentWriteId;\r\n });\r\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\r\n let snapToSend = latestState;\r\n const latestHash = latestState.hash();\r\n for (let i = 0; i < queue.length; i++) {\r\n const txn = queue[i];\r\n assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');\r\n txn.status = 1 /* TransactionStatus.SENT */;\r\n txn.retryCount++;\r\n const relativePath = newRelativePath(path, txn.path);\r\n // If we've gotten to this point, the output snapshot must be defined.\r\n snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);\r\n }\r\n const dataToSend = snapToSend.val(true);\r\n const pathToSend = path;\r\n // Send the put.\r\n repo.server_.put(pathToSend.toString(), dataToSend, (status) => {\r\n repoLog(repo, 'transaction put response', {\r\n path: pathToSend.toString(),\r\n status\r\n });\r\n let events = [];\r\n if (status === 'ok') {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more\r\n // transactions or sets.\r\n const callbacks = [];\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 2 /* TransactionStatus.COMPLETED */;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));\r\n if (queue[i].onComplete) {\r\n // We never unset the output snapshot, and given that this\r\n // transaction is complete, it should be set\r\n callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));\r\n }\r\n queue[i].unwatcher();\r\n }\r\n // Now remove the completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));\r\n // There may be pending transactions that we can now send.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n // Finally, trigger onComplete callbacks.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n else {\r\n // transactions are no longer sent. Update their status appropriately.\r\n if (status === 'datastale') {\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {\r\n queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\r\n }\r\n else {\r\n queue[i].status = 0 /* TransactionStatus.RUN */;\r\n }\r\n }\r\n }\r\n else {\r\n warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\r\n queue[i].abortReason = status;\r\n }\r\n }\r\n repoRerunTransactions(repo, path);\r\n }\r\n }, latestHash);\r\n}\r\n/**\r\n * Finds all transactions dependent on the data at changedPath and reruns them.\r\n *\r\n * Should be called any time cached data changes.\r\n *\r\n * Return the highest path that was affected by rerunning transactions. This\r\n * is the path at which events need to be raised for.\r\n *\r\n * @param changedPath - The path in mergedData that changed.\r\n * @returns The rootmost path that was affected by rerunning transactions.\r\n */\r\nfunction repoRerunTransactions(repo, changedPath) {\r\n const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);\r\n const path = treeGetPath(rootMostTransactionNode);\r\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\r\n repoRerunTransactionQueue(repo, queue, path);\r\n return path;\r\n}\r\n/**\r\n * Does all the work of rerunning transactions (as well as cleans up aborted\r\n * transactions and whatnot).\r\n *\r\n * @param queue - The queue of transactions to run.\r\n * @param path - The path the queue is for.\r\n */\r\nfunction repoRerunTransactionQueue(repo, queue, path) {\r\n if (queue.length === 0) {\r\n return; // Nothing to do!\r\n }\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions or\r\n // sets.\r\n const callbacks = [];\r\n let events = [];\r\n // Ignore all of the sets we're going to re-run.\r\n const txnsToRerun = queue.filter(q => {\r\n return q.status === 0 /* TransactionStatus.RUN */;\r\n });\r\n const setsToIgnore = txnsToRerun.map(q => {\r\n return q.currentWriteId;\r\n });\r\n for (let i = 0; i < queue.length; i++) {\r\n const transaction = queue[i];\r\n const relativePath = newRelativePath(path, transaction.path);\r\n let abortTransaction = false, abortReason;\r\n assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\r\n if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {\r\n abortTransaction = true;\r\n abortReason = transaction.abortReason;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else if (transaction.status === 0 /* TransactionStatus.RUN */) {\r\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\r\n abortTransaction = true;\r\n abortReason = 'maxretry';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else {\r\n // This code reruns a transaction\r\n const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);\r\n transaction.currentInputSnapshot = currentNode;\r\n const newData = queue[i].update(currentNode.val());\r\n if (newData !== undefined) {\r\n validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\r\n let newDataNode = nodeFromJSON(newData);\r\n const hasExplicitPriority = typeof newData === 'object' &&\r\n newData != null &&\r\n contains(newData, '.priority');\r\n if (!hasExplicitPriority) {\r\n // Keep the old priority if there wasn't a priority explicitly specified.\r\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\r\n }\r\n const oldWriteId = transaction.currentWriteId;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);\r\n transaction.currentOutputSnapshotRaw = newDataNode;\r\n transaction.currentOutputSnapshotResolved = newNodeResolved;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n // Mutates setsToIgnore in place\r\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\r\n events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));\r\n }\r\n else {\r\n abortTransaction = true;\r\n abortReason = 'nodata';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n }\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n events = [];\r\n if (abortTransaction) {\r\n // Abort.\r\n queue[i].status = 2 /* TransactionStatus.COMPLETED */;\r\n // Removing a listener can trigger pruning which can muck with\r\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\r\n // until we're done.\r\n (function (unwatcher) {\r\n setTimeout(unwatcher, Math.floor(0));\r\n })(queue[i].unwatcher);\r\n if (queue[i].onComplete) {\r\n if (abortReason === 'nodata') {\r\n callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));\r\n }\r\n else {\r\n callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));\r\n }\r\n }\r\n }\r\n }\r\n // Clean up completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\r\n // Now fire callbacks, now that we're in a good, known state.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n // Try to send the transaction result to the server.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n}\r\n/**\r\n * Returns the rootmost ancestor node of the specified path that has a pending\r\n * transaction on it, or just returns the node for the given path if there are\r\n * no pending transactions on any ancestor.\r\n *\r\n * @param path - The location to start at.\r\n * @returns The rootmost node with a transaction.\r\n */\r\nfunction repoGetAncestorTransactionNode(repo, path) {\r\n let front;\r\n // Start at the root and walk deeper into the tree towards path until we\r\n // find a node with pending transactions.\r\n let transactionNode = repo.transactionQueueTree_;\r\n front = pathGetFront(path);\r\n while (front !== null && treeGetValue(transactionNode) === undefined) {\r\n transactionNode = treeSubTree(transactionNode, front);\r\n path = pathPopFront(path);\r\n front = pathGetFront(path);\r\n }\r\n return transactionNode;\r\n}\r\n/**\r\n * Builds the queue of all transactions at or below the specified\r\n * transactionNode.\r\n *\r\n * @param transactionNode\r\n * @returns The generated queue.\r\n */\r\nfunction repoBuildTransactionQueue(repo, transactionNode) {\r\n // Walk any child transaction queues and aggregate them into a single queue.\r\n const transactionQueue = [];\r\n repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);\r\n // Sort them by the order the transactions were created.\r\n transactionQueue.sort((a, b) => a.order - b.order);\r\n return transactionQueue;\r\n}\r\nfunction repoAggregateTransactionQueuesForNode(repo, node, queue) {\r\n const nodeQueue = treeGetValue(node);\r\n if (nodeQueue) {\r\n for (let i = 0; i < nodeQueue.length; i++) {\r\n queue.push(nodeQueue[i]);\r\n }\r\n }\r\n treeForEachChild(node, child => {\r\n repoAggregateTransactionQueuesForNode(repo, child, queue);\r\n });\r\n}\r\n/**\r\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\r\n */\r\nfunction repoPruneCompletedTransactionsBelowNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n let to = 0;\r\n for (let from = 0; from < queue.length; from++) {\r\n if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {\r\n queue[to] = queue[from];\r\n to++;\r\n }\r\n }\r\n queue.length = to;\r\n treeSetValue(node, queue.length > 0 ? queue : undefined);\r\n }\r\n treeForEachChild(node, childNode => {\r\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\r\n });\r\n}\r\n/**\r\n * Aborts all transactions on ancestors or descendants of the specified path.\r\n * Called when doing a set() or update() since we consider them incompatible\r\n * with transactions.\r\n *\r\n * @param path - Path for which we want to abort related transactions.\r\n */\r\nfunction repoAbortTransactions(repo, path) {\r\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\r\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\r\n treeForEachAncestor(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n repoAbortTransactionsOnNode(repo, transactionNode);\r\n treeForEachDescendant(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n return affectedPath;\r\n}\r\n/**\r\n * Abort transactions stored in this transaction queue node.\r\n *\r\n * @param node - Node to abort transactions for.\r\n */\r\nfunction repoAbortTransactionsOnNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions\r\n // or sets.\r\n const callbacks = [];\r\n // Go through queue. Any already-sent transactions must be marked for\r\n // abort, while the unsent ones can be immediately aborted and removed.\r\n let events = [];\r\n let lastSent = -1;\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;\r\n else if (queue[i].status === 1 /* TransactionStatus.SENT */) {\r\n assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\r\n lastSent = i;\r\n // Mark transaction for abort when it comes back.\r\n queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;\r\n queue[i].abortReason = 'set';\r\n }\r\n else {\r\n assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');\r\n // We can abort it immediately.\r\n queue[i].unwatcher();\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));\r\n if (queue[i].onComplete) {\r\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));\r\n }\r\n }\r\n }\r\n if (lastSent === -1) {\r\n // We're not waiting for any sent transactions. We can clear the queue.\r\n treeSetValue(node, undefined);\r\n }\r\n else {\r\n // Remove the transactions we aborted.\r\n queue.length = lastSent + 1;\r\n }\r\n // Now fire the callbacks.\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\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\nfunction decodePath(pathString) {\r\n let pathStringDecoded = '';\r\n const pieces = pathString.split('/');\r\n for (let i = 0; i < pieces.length; i++) {\r\n if (pieces[i].length > 0) {\r\n let piece = pieces[i];\r\n try {\r\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\r\n }\r\n catch (e) { }\r\n pathStringDecoded += '/' + piece;\r\n }\r\n }\r\n return pathStringDecoded;\r\n}\r\n/**\r\n * @returns key value hash\r\n */\r\nfunction decodeQuery(queryString) {\r\n const results = {};\r\n if (queryString.charAt(0) === '?') {\r\n queryString = queryString.substring(1);\r\n }\r\n for (const segment of queryString.split('&')) {\r\n if (segment.length === 0) {\r\n continue;\r\n }\r\n const kv = segment.split('=');\r\n if (kv.length === 2) {\r\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\r\n }\r\n else {\r\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\r\n }\r\n }\r\n return results;\r\n}\r\nconst parseRepoInfo = function (dataURL, nodeAdmin) {\r\n const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;\r\n if (parsedUrl.domain === 'firebase.com') {\r\n fatal(parsedUrl.host +\r\n ' is no longer supported. ' +\r\n 'Please use .firebaseio.com instead');\r\n }\r\n // Catch common error of uninitialized namespace value.\r\n if ((!namespace || namespace === 'undefined') &&\r\n parsedUrl.domain !== 'localhost') {\r\n fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\r\n }\r\n if (!parsedUrl.secure) {\r\n warnIfPageIsSecure();\r\n }\r\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\r\n return {\r\n repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, \r\n /*persistenceKey=*/ '', \r\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),\r\n path: new Path(parsedUrl.pathString)\r\n };\r\n};\r\nconst parseDatabaseURL = function (dataURL) {\r\n // Default to empty strings in the event of a malformed string.\r\n let host = '', domain = '', subdomain = '', pathString = '', namespace = '';\r\n // Always default to SSL, unless otherwise specified.\r\n let secure = true, scheme = 'https', port = 443;\r\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\r\n if (typeof dataURL === 'string') {\r\n // Parse scheme.\r\n let colonInd = dataURL.indexOf('//');\r\n if (colonInd >= 0) {\r\n scheme = dataURL.substring(0, colonInd - 1);\r\n dataURL = dataURL.substring(colonInd + 2);\r\n }\r\n // Parse host, path, and query string.\r\n let slashInd = dataURL.indexOf('/');\r\n if (slashInd === -1) {\r\n slashInd = dataURL.length;\r\n }\r\n let questionMarkInd = dataURL.indexOf('?');\r\n if (questionMarkInd === -1) {\r\n questionMarkInd = dataURL.length;\r\n }\r\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\r\n if (slashInd < questionMarkInd) {\r\n // For pathString, questionMarkInd will always come after slashInd\r\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\r\n }\r\n const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\r\n // If we have a port, use scheme for determining if it's secure.\r\n colonInd = host.indexOf(':');\r\n if (colonInd >= 0) {\r\n secure = scheme === 'https' || scheme === 'wss';\r\n port = parseInt(host.substring(colonInd + 1), 10);\r\n }\r\n else {\r\n colonInd = host.length;\r\n }\r\n const hostWithoutPort = host.slice(0, colonInd);\r\n if (hostWithoutPort.toLowerCase() === 'localhost') {\r\n domain = 'localhost';\r\n }\r\n else if (hostWithoutPort.split('.').length <= 2) {\r\n domain = hostWithoutPort;\r\n }\r\n else {\r\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\r\n const dotInd = host.indexOf('.');\r\n subdomain = host.substring(0, dotInd).toLowerCase();\r\n domain = host.substring(dotInd + 1);\r\n // Normalize namespaces to lowercase to share storage / connection.\r\n namespace = subdomain;\r\n }\r\n // Always treat the value of the `ns` as the namespace name if it is present.\r\n if ('ns' in queryParams) {\r\n namespace = queryParams['ns'];\r\n }\r\n }\r\n return {\r\n host,\r\n port,\r\n domain,\r\n subdomain,\r\n secure,\r\n scheme,\r\n pathString,\r\n namespace\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// Modeled after base64 web-safe chars, but ordered by ASCII.\r\nconst PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\r\n/**\r\n * Fancy ID generator that creates 20-character string identifiers with the\r\n * following properties:\r\n *\r\n * 1. They're based on timestamp so that they sort *after* any existing ids.\r\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\r\n * collide with other clients' IDs.\r\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\r\n * that will sort properly).\r\n * 4. They're monotonically increasing. Even if you generate more than one in\r\n * the same timestamp, the latter ones will sort after the former ones. We do\r\n * this by using the previous random bits but \"incrementing\" them by 1 (only\r\n * in the case of a timestamp collision).\r\n */\r\nconst nextPushId = (function () {\r\n // Timestamp of last push, used to prevent local collisions if you push twice\r\n // in one ms.\r\n let lastPushTime = 0;\r\n // We generate 72-bits of randomness which get turned into 12 characters and\r\n // appended to the timestamp to prevent collisions with other clients. We\r\n // store the last characters we generated because in the event of a collision,\r\n // we'll use those same characters except \"incremented\" by one.\r\n const lastRandChars = [];\r\n return function (now) {\r\n const duplicateTime = now === lastPushTime;\r\n lastPushTime = now;\r\n let i;\r\n const timeStampChars = new Array(8);\r\n for (i = 7; i >= 0; i--) {\r\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\r\n // NOTE: Can't use << here because javascript will convert to int and lose\r\n // the upper bits.\r\n now = Math.floor(now / 64);\r\n }\r\n assert(now === 0, 'Cannot push at time == 0');\r\n let id = timeStampChars.join('');\r\n if (!duplicateTime) {\r\n for (i = 0; i < 12; i++) {\r\n lastRandChars[i] = Math.floor(Math.random() * 64);\r\n }\r\n }\r\n else {\r\n // If the timestamp hasn't changed since last push, use the same random\r\n // number, except incremented by 1.\r\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\r\n lastRandChars[i] = 0;\r\n }\r\n lastRandChars[i]++;\r\n }\r\n for (i = 0; i < 12; i++) {\r\n id += PUSH_CHARS.charAt(lastRandChars[i]);\r\n }\r\n assert(id.length === 20, 'nextPushId: Length should be 20.');\r\n return id;\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/**\r\n * Encapsulates the data needed to raise an event\r\n */\r\nclass DataEvent {\r\n /**\r\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\r\n * @param eventRegistration - The function to call to with the event data. User provided\r\n * @param snapshot - The data backing the event\r\n * @param prevName - Optional, the name of the previous child for child_* events.\r\n */\r\n constructor(eventType, eventRegistration, snapshot, prevName) {\r\n this.eventType = eventType;\r\n this.eventRegistration = eventRegistration;\r\n this.snapshot = snapshot;\r\n this.prevName = prevName;\r\n }\r\n getPath() {\r\n const ref = this.snapshot.ref;\r\n if (this.eventType === 'value') {\r\n return ref._path;\r\n }\r\n else {\r\n return ref.parent._path;\r\n }\r\n }\r\n getEventType() {\r\n return this.eventType;\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return (this.getPath().toString() +\r\n ':' +\r\n this.eventType +\r\n ':' +\r\n stringify(this.snapshot.exportVal()));\r\n }\r\n}\r\nclass CancelEvent {\r\n constructor(eventRegistration, error, path) {\r\n this.eventRegistration = eventRegistration;\r\n this.error = error;\r\n this.path = path;\r\n }\r\n getPath() {\r\n return this.path;\r\n }\r\n getEventType() {\r\n return 'cancel';\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return this.path.toString() + ':cancel';\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/**\r\n * A wrapper class that converts events from the database@exp SDK to the legacy\r\n * Database SDK. Events are not converted directly as event registration relies\r\n * on reference comparison of the original user callback (see `matches()`) and\r\n * relies on equality of the legacy SDK's `context` object.\r\n */\r\nclass CallbackContext {\r\n constructor(snapshotCallback, cancelCallback) {\r\n this.snapshotCallback = snapshotCallback;\r\n this.cancelCallback = cancelCallback;\r\n }\r\n onValue(expDataSnapshot, previousChildName) {\r\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\r\n }\r\n onCancel(error) {\r\n assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');\r\n return this.cancelCallback.call(null, error);\r\n }\r\n get hasCancelCallback() {\r\n return !!this.cancelCallback;\r\n }\r\n matches(other) {\r\n return (this.snapshotCallback === other.snapshotCallback ||\r\n (this.snapshotCallback.userCallback !== undefined &&\r\n this.snapshotCallback.userCallback ===\r\n other.snapshotCallback.userCallback &&\r\n this.snapshotCallback.context === other.snapshotCallback.context));\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\n/**\r\n * The `onDisconnect` class allows you to write or clear data when your client\r\n * disconnects from the Database server. These updates occur whether your\r\n * client disconnects cleanly or not, so you can rely on them to clean up data\r\n * even if a connection is dropped or a client crashes.\r\n *\r\n * The `onDisconnect` class is most commonly used to manage presence in\r\n * applications where it is useful to detect how many clients are connected and\r\n * when other clients disconnect. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * To avoid problems when a connection is dropped before the requests can be\r\n * transferred to the Database server, these functions should be called before\r\n * writing any data.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time you reconnect.\r\n */\r\nclass OnDisconnect {\r\n /** @hideconstructor */\r\n constructor(_repo, _path) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n }\r\n /**\r\n * Cancels all previously queued `onDisconnect()` set or update events for this\r\n * location and all children.\r\n *\r\n * If a write has been queued for this location via a `set()` or `update()` at a\r\n * parent location, the write at this location will be canceled, though writes\r\n * to sibling locations will still occur.\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n cancel() {\r\n const deferred = new Deferred();\r\n repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is deleted when the client is disconnected\r\n * (due to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n remove() {\r\n validateWritablePath('OnDisconnect.remove', this._path);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value when the\r\n * client is disconnected (due to closing the browser, navigating to a new page,\r\n * or network issues).\r\n *\r\n * `set()` is especially useful for implementing \"presence\" systems, where a\r\n * value should be changed or cleared when a user disconnects so that they\r\n * appear \"offline\" to other users. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time.\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n set(value) {\r\n validateWritablePath('OnDisconnect.set', this._path);\r\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value and priority\r\n * when the client is disconnected (due to closing the browser, navigating to a\r\n * new page, or network issues).\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n setWithPriority(value, priority) {\r\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\r\n validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);\r\n validatePriority('OnDisconnect.setWithPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Writes multiple values at this location when the client is disconnected (due\r\n * to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\r\n * from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n update(values) {\r\n validateWritablePath('OnDisconnect.update', this._path);\r\n validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\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 * @internal\r\n */\r\nclass QueryImpl {\r\n /**\r\n * @hideconstructor\r\n */\r\n constructor(_repo, _path, _queryParams, _orderByCalled) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n this._queryParams = _queryParams;\r\n this._orderByCalled = _orderByCalled;\r\n }\r\n get key() {\r\n if (pathIsEmpty(this._path)) {\r\n return null;\r\n }\r\n else {\r\n return pathGetBack(this._path);\r\n }\r\n }\r\n get ref() {\r\n return new ReferenceImpl(this._repo, this._path);\r\n }\r\n get _queryIdentifier() {\r\n const obj = queryParamsGetQueryObject(this._queryParams);\r\n const id = ObjectToUniqueKey(obj);\r\n return id === '{}' ? 'default' : id;\r\n }\r\n /**\r\n * An object representation of the query parameters used by this Query.\r\n */\r\n get _queryObject() {\r\n return queryParamsGetQueryObject(this._queryParams);\r\n }\r\n isEqual(other) {\r\n other = getModularInstance(other);\r\n if (!(other instanceof QueryImpl)) {\r\n return false;\r\n }\r\n const sameRepo = this._repo === other._repo;\r\n const samePath = pathEquals(this._path, other._path);\r\n const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;\r\n return sameRepo && samePath && sameQueryIdentifier;\r\n }\r\n toJSON() {\r\n return this.toString();\r\n }\r\n toString() {\r\n return this._repo.toString() + pathToUrlEncodedString(this._path);\r\n }\r\n}\r\n/**\r\n * Validates that no other order by call has been made\r\n */\r\nfunction validateNoPreviousOrderByCall(query, fnName) {\r\n if (query._orderByCalled === true) {\r\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\r\n }\r\n}\r\n/**\r\n * Validates start/end values for queries.\r\n */\r\nfunction validateQueryEndpoints(params) {\r\n let startNode = null;\r\n let endNode = null;\r\n if (params.hasStart()) {\r\n startNode = params.getIndexStartValue();\r\n }\r\n if (params.hasEnd()) {\r\n endNode = params.getIndexEndValue();\r\n }\r\n if (params.getIndex() === KEY_INDEX) {\r\n const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\r\n 'startAt(), endAt(), or equalTo().';\r\n const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\r\n 'endAt(), endBefore(), or equalTo() must be a string.';\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n if (startName !== MIN_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof startNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n if (endName !== MAX_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof endNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n }\r\n else if (params.getIndex() === PRIORITY_INDEX) {\r\n if ((startNode != null && !isValidPriority(startNode)) ||\r\n (endNode != null && !isValidPriority(endNode))) {\r\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\r\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\r\n '(null, a number, or a string).');\r\n }\r\n }\r\n else {\r\n assert(params.getIndex() instanceof PathIndex ||\r\n params.getIndex() === VALUE_INDEX, 'unknown index type.');\r\n if ((startNode != null && typeof startNode === 'object') ||\r\n (endNode != null && typeof endNode === 'object')) {\r\n throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\r\n 'equalTo() cannot be an object.');\r\n }\r\n }\r\n}\r\n/**\r\n * Validates that limit* has been called with the correct combination of parameters\r\n */\r\nfunction validateLimit(params) {\r\n if (params.hasStart() &&\r\n params.hasEnd() &&\r\n params.hasLimit() &&\r\n !params.hasAnchoredLimit()) {\r\n throw new Error(\"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\r\n 'limitToFirst() or limitToLast() instead.');\r\n }\r\n}\r\n/**\r\n * @internal\r\n */\r\nclass ReferenceImpl extends QueryImpl {\r\n /** @hideconstructor */\r\n constructor(repo, path) {\r\n super(repo, path, new QueryParams(), false);\r\n }\r\n get parent() {\r\n const parentPath = pathParent(this._path);\r\n return parentPath === null\r\n ? null\r\n : new ReferenceImpl(this._repo, parentPath);\r\n }\r\n get root() {\r\n let ref = this;\r\n while (ref.parent !== null) {\r\n ref = ref.parent;\r\n }\r\n return ref;\r\n }\r\n}\r\n/**\r\n * A `DataSnapshot` contains data from a Database location.\r\n *\r\n * Any time you read data from the Database, you receive the data as a\r\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\r\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\r\n * JavaScript object by calling the `val()` method. Alternatively, you can\r\n * traverse into the snapshot by calling `child()` to return child snapshots\r\n * (which you could then call `val()` on).\r\n *\r\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\r\n * a Database location. It cannot be modified and will never change (to modify\r\n * data, you always call the `set()` method on a `Reference` directly).\r\n */\r\nclass DataSnapshot {\r\n /**\r\n * @param _node - A SnapshotNode to wrap.\r\n * @param ref - The location this snapshot came from.\r\n * @param _index - The iteration order for this snapshot\r\n * @hideconstructor\r\n */\r\n constructor(_node, \r\n /**\r\n * The location of this DataSnapshot.\r\n */\r\n ref, _index) {\r\n this._node = _node;\r\n this.ref = ref;\r\n this._index = _index;\r\n }\r\n /**\r\n * Gets the priority value of the data in this `DataSnapshot`.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\r\n * ).\r\n */\r\n get priority() {\r\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\r\n return this._node.getPriority().val();\r\n }\r\n /**\r\n * The key (last part of the path) of the location of this `DataSnapshot`.\r\n *\r\n * The last token in a Database location is considered its key. For example,\r\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\r\n * `DataSnapshot` will return the key for the location that generated it.\r\n * However, accessing the key on the root URL of a Database will return\r\n * `null`.\r\n */\r\n get key() {\r\n return this.ref.key;\r\n }\r\n /** Returns the number of child properties of this `DataSnapshot`. */\r\n get size() {\r\n return this._node.numChildren();\r\n }\r\n /**\r\n * Gets another `DataSnapshot` for the location at the specified relative path.\r\n *\r\n * Passing a relative path to the `child()` method of a DataSnapshot returns\r\n * another `DataSnapshot` for the location at the specified relative path. The\r\n * relative path can either be a simple child name (for example, \"ada\") or a\r\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\r\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\r\n * whose value is `null`) is returned.\r\n *\r\n * @param path - A relative path to the location of child data.\r\n */\r\n child(path) {\r\n const childPath = new Path(path);\r\n const childRef = child(this.ref, path);\r\n return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);\r\n }\r\n /**\r\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\r\n * efficient than using `snapshot.val() !== null`.\r\n */\r\n exists() {\r\n return !this._node.isEmpty();\r\n }\r\n /**\r\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\r\n *\r\n * The `exportVal()` method is similar to `val()`, except priority information\r\n * is included (if available), making it suitable for backing up your data.\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n exportVal() {\r\n return this._node.val(true);\r\n }\r\n /**\r\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\r\n *\r\n * Because of the way JavaScript objects work, the ordering of data in the\r\n * JavaScript object returned by `val()` is not guaranteed to match the\r\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\r\n * where `forEach()` comes in handy. It guarantees the children of a\r\n * `DataSnapshot` will be iterated in their query order.\r\n *\r\n * If no explicit `orderBy*()` method is used, results are returned\r\n * ordered by key (unless priorities are used, in which case, results are\r\n * returned by priority).\r\n *\r\n * @param action - A function that will be called for each child DataSnapshot.\r\n * The callback can return true to cancel further enumeration.\r\n * @returns true if enumeration was canceled due to your callback returning\r\n * true.\r\n */\r\n forEach(action) {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n const childrenNode = this._node;\r\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\r\n return !!childrenNode.forEachChild(this._index, (key, node) => {\r\n return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));\r\n });\r\n }\r\n /**\r\n * Returns true if the specified child path has (non-null) data.\r\n *\r\n * @param path - A relative path to the location of a potential child.\r\n * @returns `true` if data exists at the specified child path; else\r\n * `false`.\r\n */\r\n hasChild(path) {\r\n const childPath = new Path(path);\r\n return !this._node.getChild(childPath).isEmpty();\r\n }\r\n /**\r\n * Returns whether or not the `DataSnapshot` has any non-`null` child\r\n * properties.\r\n *\r\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\r\n * children. If it does, you can enumerate them using `forEach()`. If it\r\n * doesn't, then either this snapshot contains a primitive value (which can be\r\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\r\n * `null`).\r\n *\r\n * @returns true if this snapshot has any children; else false.\r\n */\r\n hasChildren() {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n return !this._node.isEmpty();\r\n }\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return this.exportVal();\r\n }\r\n /**\r\n * Extracts a JavaScript value from a `DataSnapshot`.\r\n *\r\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\r\n * scalar type (string, number, or boolean), an array, or an object. It may\r\n * also return null, indicating that the `DataSnapshot` is empty (contains no\r\n * data).\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n val() {\r\n return this._node.val();\r\n }\r\n}\r\n/**\r\n *\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided path. If no path is provided, the `Reference`\r\n * will point to the root of the Database.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param path - Optional path representing the location the returned\r\n * `Reference` will point. If not provided, the returned `Reference` will\r\n * point to the root of the Database.\r\n * @returns If a path is provided, a `Reference`\r\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\r\n * root of the Database.\r\n */\r\nfunction ref(db, path) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('ref');\r\n return path !== undefined ? child(db._root, path) : db._root;\r\n}\r\n/**\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided Firebase URL.\r\n *\r\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\r\n * has a different domain than the current `Database` instance.\r\n *\r\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\r\n * and are not applied to the returned `Reference`.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param url - The Firebase URL at which the returned `Reference` will\r\n * point.\r\n * @returns A `Reference` pointing to the provided\r\n * Firebase URL.\r\n */\r\nfunction refFromURL(db, url) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('refFromURL');\r\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\r\n validateUrl('refFromURL', parsedURL);\r\n const repoInfo = parsedURL.repoInfo;\r\n if (!db._repo.repoInfo_.isCustomHost() &&\r\n repoInfo.host !== db._repo.repoInfo_.host) {\r\n fatal('refFromURL' +\r\n ': Host name does not match the current database: ' +\r\n '(found ' +\r\n repoInfo.host +\r\n ' but expected ' +\r\n db._repo.repoInfo_.host +\r\n ')');\r\n }\r\n return ref(db, parsedURL.path.toString());\r\n}\r\n/**\r\n * Gets a `Reference` for the location at the specified relative path.\r\n *\r\n * The relative path can either be a simple child name (for example, \"ada\") or\r\n * a deeper slash-separated path (for example, \"ada/name/first\").\r\n *\r\n * @param parent - The parent location.\r\n * @param path - A relative path from this location to the desired child\r\n * location.\r\n * @returns The specified child location.\r\n */\r\nfunction child(parent, path) {\r\n parent = getModularInstance(parent);\r\n if (pathGetFront(parent._path) === null) {\r\n validateRootPathString('child', 'path', path, false);\r\n }\r\n else {\r\n validatePathString('child', 'path', path, false);\r\n }\r\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\r\n}\r\n/**\r\n * Returns an `OnDisconnect` object - see\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information on how to use it.\r\n *\r\n * @param ref - The reference to add OnDisconnect triggers for.\r\n */\r\nfunction onDisconnect(ref) {\r\n ref = getModularInstance(ref);\r\n return new OnDisconnect(ref._repo, ref._path);\r\n}\r\n/**\r\n * Generates a new child location using a unique key and returns its\r\n * `Reference`.\r\n *\r\n * This is the most common pattern for adding data to a collection of items.\r\n *\r\n * If you provide a value to `push()`, the value is written to the\r\n * generated location. If you don't pass a value, nothing is written to the\r\n * database and the child remains empty (but you can use the `Reference`\r\n * elsewhere).\r\n *\r\n * The unique keys generated by `push()` are ordered by the current time, so the\r\n * resulting list of items is chronologically sorted. The keys are also\r\n * designed to be unguessable (they contain 72 random bits of entropy).\r\n *\r\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\r\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\r\n *\r\n * @param parent - The parent location.\r\n * @param value - Optional value to be written at the generated location.\r\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\r\n * but can be used immediately as the `Reference` to the child location.\r\n */\r\nfunction push(parent, value) {\r\n parent = getModularInstance(parent);\r\n validateWritablePath('push', parent._path);\r\n validateFirebaseDataArg('push', value, parent._path, true);\r\n const now = repoServerTime(parent._repo);\r\n const name = nextPushId(now);\r\n // push() returns a ThennableReference whose promise is fulfilled with a\r\n // regular Reference. We use child() to create handles to two different\r\n // references. The first is turned into a ThennableReference below by adding\r\n // then() and catch() methods and is used as the return value of push(). The\r\n // second remains a regular Reference and is used as the fulfilled value of\r\n // the first ThennableReference.\r\n const thenablePushRef = child(parent, name);\r\n const pushRef = child(parent, name);\r\n let promise;\r\n if (value != null) {\r\n promise = set(pushRef, value).then(() => pushRef);\r\n }\r\n else {\r\n promise = Promise.resolve(pushRef);\r\n }\r\n thenablePushRef.then = promise.then.bind(promise);\r\n thenablePushRef.catch = promise.then.bind(promise, undefined);\r\n return thenablePushRef;\r\n}\r\n/**\r\n * Removes the data at this Database location.\r\n *\r\n * Any data at child locations will also be deleted.\r\n *\r\n * The effect of the remove will be visible immediately and the corresponding\r\n * event 'value' will be triggered. Synchronization of the remove to the\r\n * Firebase servers will also be started, and the returned Promise will resolve\r\n * when complete. If provided, the onComplete callback will be called\r\n * asynchronously after synchronization has finished.\r\n *\r\n * @param ref - The location to remove.\r\n * @returns Resolves when remove on server is complete.\r\n */\r\nfunction remove(ref) {\r\n validateWritablePath('remove', ref._path);\r\n return set(ref, null);\r\n}\r\n/**\r\n * Writes data to this Database location.\r\n *\r\n * This will overwrite any data at this location and all child locations.\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\r\n * all data at this location and all child locations will be deleted.\r\n *\r\n * `set()` will remove any priority stored at this location, so if priority is\r\n * meant to be preserved, you need to use `setWithPriority()` instead.\r\n *\r\n * Note that modifying data with `set()` will cancel any pending transactions\r\n * at that location, so extreme care should be taken if mixing `set()` and\r\n * `transaction()` to modify the same data.\r\n *\r\n * A single `set()` will generate a single \"value\" event at the location where\r\n * the `set()` was performed.\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction set(ref, value) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('set', ref._path);\r\n validateFirebaseDataArg('set', value, ref._path, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, \r\n /*priority=*/ null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Sets a priority for the data at this Database location.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setPriority(ref, priority) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('setPriority', ref._path);\r\n validatePriority('setPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes data the Database location. Like `set()` but also specifies the\r\n * priority for that data.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setWithPriority(ref, value, priority) {\r\n validateWritablePath('setWithPriority', ref._path);\r\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\r\n validatePriority('setWithPriority', priority, false);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\r\n }\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes multiple values to the Database at once.\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example,\r\n * \"name/first\") from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * A single `update()` will generate a single \"value\" event at the location\r\n * where the `update()` was performed, regardless of how many children were\r\n * modified.\r\n *\r\n * Note that modifying data with `update()` will cancel any pending\r\n * transactions at that location, so extreme care should be taken if mixing\r\n * `update()` and `transaction()` to modify the same data.\r\n *\r\n * Passing `null` to `update()` will remove the data at this location.\r\n *\r\n * See\r\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\r\n *\r\n * @param ref - The location to write to.\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when update on server is complete.\r\n */\r\nfunction update(ref, values) {\r\n validateFirebaseMergeDataArg('update', values, ref._path, false);\r\n const deferred = new Deferred();\r\n repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Gets the most up-to-date result for this query.\r\n *\r\n * @param query - The query to run.\r\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\r\n * available, or rejects if the client is unable to return a value (e.g., if the\r\n * server is unreachable and there is nothing cached).\r\n */\r\nfunction get(query) {\r\n query = getModularInstance(query);\r\n const callbackContext = new CallbackContext(() => { });\r\n const container = new ValueEventRegistration(callbackContext);\r\n return repoGetValue(query._repo, query, container).then(node => {\r\n return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());\r\n });\r\n}\r\n/**\r\n * Represents registration for 'value' events.\r\n */\r\nclass ValueEventRegistration {\r\n constructor(callbackContext) {\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n return eventType === 'value';\r\n }\r\n createEvent(change, query) {\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, null);\r\n }\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n matches(other) {\r\n if (!(other instanceof ValueEventRegistration)) {\r\n return false;\r\n }\r\n else if (!other.callbackContext || !this.callbackContext) {\r\n // If no callback specified, we consider it to match any callback.\r\n return true;\r\n }\r\n else {\r\n return other.callbackContext.matches(this.callbackContext);\r\n }\r\n }\r\n hasAnyCallback() {\r\n return this.callbackContext !== null;\r\n }\r\n}\r\n/**\r\n * Represents the registration of a child_x event.\r\n */\r\nclass ChildEventRegistration {\r\n constructor(eventType, callbackContext) {\r\n this.eventType = eventType;\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\r\n eventToCheck =\r\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\r\n return this.eventType === eventToCheck;\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n createEvent(change, query) {\r\n assert(change.childName != null, 'Child events should have a childName.');\r\n const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);\r\n }\r\n }\r\n matches(other) {\r\n if (other instanceof ChildEventRegistration) {\r\n return (this.eventType === other.eventType &&\r\n (!this.callbackContext ||\r\n !other.callbackContext ||\r\n this.callbackContext.matches(other.callbackContext)));\r\n }\r\n return false;\r\n }\r\n hasAnyCallback() {\r\n return !!this.callbackContext;\r\n }\r\n}\r\nfunction addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {\r\n let cancelCallback;\r\n if (typeof cancelCallbackOrListenOptions === 'object') {\r\n cancelCallback = undefined;\r\n options = cancelCallbackOrListenOptions;\r\n }\r\n if (typeof cancelCallbackOrListenOptions === 'function') {\r\n cancelCallback = cancelCallbackOrListenOptions;\r\n }\r\n if (options && options.onlyOnce) {\r\n const userCallback = callback;\r\n const onceCallback = (dataSnapshot, previousChildName) => {\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n userCallback(dataSnapshot, previousChildName);\r\n };\r\n onceCallback.userCallback = callback.userCallback;\r\n onceCallback.context = callback.context;\r\n callback = onceCallback;\r\n }\r\n const callbackContext = new CallbackContext(callback, cancelCallback || undefined);\r\n const container = eventType === 'value'\r\n ? new ValueEventRegistration(callbackContext)\r\n : new ChildEventRegistration(eventType, callbackContext);\r\n repoAddEventCallbackForQuery(query._repo, query, container);\r\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\nfunction onValue(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\n/**\r\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\r\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\r\n * the respective `on*` callbacks.\r\n *\r\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\r\n * will not automatically remove listeners registered on child nodes, `off()`\r\n * must also be called on any child listeners to remove the callback.\r\n *\r\n * If a callback is not specified, all callbacks for the specified eventType\r\n * will be removed. Similarly, if no eventType is specified, all callbacks\r\n * for the `Reference` will be removed.\r\n *\r\n * Individual listeners can also be removed by invoking their unsubscribe\r\n * callbacks.\r\n *\r\n * @param query - The query that the listener was registered with.\r\n * @param eventType - One of the following strings: \"value\", \"child_added\",\r\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\r\n * for the `Reference` will be removed.\r\n * @param callback - The callback function that was passed to `on()` or\r\n * `undefined` to remove all callbacks.\r\n */\r\nfunction off(query, eventType, callback) {\r\n let container = null;\r\n const expCallback = callback ? new CallbackContext(callback) : null;\r\n if (eventType === 'value') {\r\n container = new ValueEventRegistration(expCallback);\r\n }\r\n else if (eventType) {\r\n container = new ChildEventRegistration(eventType, expCallback);\r\n }\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\n/**\r\n * A `QueryConstraint` is used to narrow the set of documents returned by a\r\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\r\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\r\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\r\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\r\n * {@link orderByValue} or {@link equalTo} and\r\n * can then be passed to {@link query} to create a new query instance that\r\n * also contains this `QueryConstraint`.\r\n */\r\nclass QueryConstraint {\r\n}\r\nclass QueryEndAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'endAt';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endAt', this._value, query._path, true);\r\n const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endAt: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name less than or equal\r\n * to the specified key.\r\n *\r\n * You can read more about `endAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to end at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end at, among the children with the previously\r\n * specified priority. This argument is only allowed if ordering by child,\r\n * value, or priority.\r\n */\r\nfunction endAt(value, key) {\r\n validateKey('endAt', 'key', key, true);\r\n return new QueryEndAtConstraint(value, key);\r\n}\r\nclass QueryEndBeforeConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'endBefore';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\r\n const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is exclusive. If only a value is provided, children\r\n * with a value less than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value less than or equal\r\n * to the specified value and a key name less than the specified key.\r\n *\r\n * @param value - The value to end before. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end before, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction endBefore(value, key) {\r\n validateKey('endBefore', 'key', key, true);\r\n return new QueryEndBeforeConstraint(value, key);\r\n}\r\nclass QueryStartAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'startAt';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAt', this._value, query._path, true);\r\n const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAt: Starting point was already set (by another call to startAt, ' +\r\n 'startBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name greater than or\r\n * equal to the specified key.\r\n *\r\n * You can read more about `startAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to start at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAt(value = null, key) {\r\n validateKey('startAt', 'key', key, true);\r\n return new QueryStartAtConstraint(value, key);\r\n}\r\nclass QueryStartAfterConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'startAfter';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\r\n const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +\r\n 'startAfter, or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is exclusive. If only a value is provided, children\r\n * with a value greater than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value greater than or equal\r\n * to the specified value and a a key name greater than the specified key.\r\n *\r\n * @param value - The value to start after. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start after. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAfter(value, key) {\r\n validateKey('startAfter', 'key', key, true);\r\n return new QueryStartAfterConstraint(value, key);\r\n}\r\nclass QueryLimitToFirstConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n this.type = 'limitToFirst';\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that if limited to the first specific number\r\n * of children.\r\n *\r\n * The `limitToFirst()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the first 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToFirst()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToFirst(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToFirst: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToFirstConstraint(limit);\r\n}\r\nclass QueryLimitToLastConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n this.type = 'limitToLast';\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that is limited to return only the last\r\n * specified number of children.\r\n *\r\n * The `limitToLast()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the last 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToLast()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToLast(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToLast: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToLastConstraint(limit);\r\n}\r\nclass QueryOrderByChildConstraint extends QueryConstraint {\r\n constructor(_path) {\r\n super();\r\n this._path = _path;\r\n this.type = 'orderByChild';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByChild');\r\n const parsedPath = new Path(this._path);\r\n if (pathIsEmpty(parsedPath)) {\r\n throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');\r\n }\r\n const index = new PathIndex(parsedPath);\r\n const newParams = queryParamsOrderBy(query._queryParams, index);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the specified child key.\r\n *\r\n * Queries can only order by one key at a time. Calling `orderByChild()`\r\n * multiple times on the same query is an error.\r\n *\r\n * Firebase queries allow you to order your data by any child key on the fly.\r\n * However, if you know in advance what your indexes will be, you can define\r\n * them via the .indexOn rule in your Security Rules for better performance. See\r\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\r\n * rule for more information.\r\n *\r\n * You can read more about `orderByChild()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n *\r\n * @param path - The path to order by.\r\n */\r\nfunction orderByChild(path) {\r\n if (path === '$key') {\r\n throw new Error('orderByChild: \"$key\" is invalid. Use orderByKey() instead.');\r\n }\r\n else if (path === '$priority') {\r\n throw new Error('orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.');\r\n }\r\n else if (path === '$value') {\r\n throw new Error('orderByChild: \"$value\" is invalid. Use orderByValue() instead.');\r\n }\r\n validatePathString('orderByChild', 'path', path, false);\r\n return new QueryOrderByChildConstraint(path);\r\n}\r\nclass QueryOrderByKeyConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByKey';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByKey');\r\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the key.\r\n *\r\n * Sorts the results of a query by their (ascending) key values.\r\n *\r\n * You can read more about `orderByKey()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByKey() {\r\n return new QueryOrderByKeyConstraint();\r\n}\r\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByPriority';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByPriority');\r\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by priority.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\r\n * for alternatives to priority.\r\n */\r\nfunction orderByPriority() {\r\n return new QueryOrderByPriorityConstraint();\r\n}\r\nclass QueryOrderByValueConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByValue';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByValue');\r\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by value.\r\n *\r\n * If the children of a query are all scalar values (string, number, or\r\n * boolean), you can order the results by their (ascending) values.\r\n *\r\n * You can read more about `orderByValue()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByValue() {\r\n return new QueryOrderByValueConstraint();\r\n}\r\nclass QueryEqualToValueConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'equalTo';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\r\n 'equalTo).');\r\n }\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\r\n 'equalTo).');\r\n }\r\n return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` that includes children that match the specified\r\n * value.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The optional key argument can be used to further limit the range of the\r\n * query. If it is specified, then children that have exactly the specified\r\n * value must also have exactly the specified key as their key name. This can be\r\n * used to filter result sets with many matches for the same value.\r\n *\r\n * You can read more about `equalTo()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to match for. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction equalTo(value, key) {\r\n validateKey('equalTo', 'key', key, true);\r\n return new QueryEqualToValueConstraint(value, key);\r\n}\r\n/**\r\n * Creates a new immutable instance of `Query` that is extended to also include\r\n * additional query constraints.\r\n *\r\n * @param query - The Query instance to use as a base for the new constraints.\r\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\r\n * @throws if any of the provided query constraints cannot be combined with the\r\n * existing or new constraints.\r\n */\r\nfunction query(query, ...queryConstraints) {\r\n let queryImpl = getModularInstance(query);\r\n for (const constraint of queryConstraints) {\r\n queryImpl = constraint._apply(queryImpl);\r\n }\r\n return queryImpl;\r\n}\r\n/**\r\n * Define reference constructor in various modules\r\n *\r\n * We are doing this here to avoid several circular\r\n * dependency issues\r\n */\r\nsyncPointSetReferenceConstructor(ReferenceImpl);\r\nsyncTreeSetReferenceConstructor(ReferenceImpl);\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 * This variable is also defined in the firebase Node.js Admin SDK. Before\r\n * modifying this definition, consult the definition in:\r\n *\r\n * https://github.com/firebase/firebase-admin-node\r\n *\r\n * and make sure the two are consistent.\r\n */\r\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\r\n/**\r\n * Creates and caches `Repo` instances.\r\n */\r\nconst repos = {};\r\n/**\r\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\r\n */\r\nlet useRestClient = false;\r\n/**\r\n * Update an existing `Repo` in place to point to a new host/port.\r\n */\r\nfunction repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {\r\n repo.repoInfo_ = new RepoInfo(`${host}:${port}`, \r\n /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, \r\n /*isUsingEmulator=*/ true);\r\n if (tokenProvider) {\r\n repo.authTokenProvider_ = tokenProvider;\r\n }\r\n}\r\n/**\r\n * This function should only ever be called to CREATE a new database instance.\r\n * @internal\r\n */\r\nfunction repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {\r\n let dbUrl = url || app.options.databaseURL;\r\n if (dbUrl === undefined) {\r\n if (!app.options.projectId) {\r\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\r\n ' a Project ID when calling firebase.initializeApp().');\r\n }\r\n log('Using default host for project ', app.options.projectId);\r\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\r\n }\r\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n let repoInfo = parsedUrl.repoInfo;\r\n let isEmulator;\r\n let dbEmulatorHost = undefined;\r\n if (typeof process !== 'undefined' && process.env) {\r\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\r\n }\r\n if (dbEmulatorHost) {\r\n isEmulator = true;\r\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\r\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n repoInfo = parsedUrl.repoInfo;\r\n }\r\n else {\r\n isEmulator = !parsedUrl.repoInfo.secure;\r\n }\r\n const authTokenProvider = nodeAdmin && isEmulator\r\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\r\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\r\n validateUrl('Invalid Firebase Database URL', parsedUrl);\r\n if (!pathIsEmpty(parsedUrl.path)) {\r\n fatal('Database URL must point to the root of a Firebase Database ' +\r\n '(not including a child path).');\r\n }\r\n const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));\r\n return new Database(repo, app);\r\n}\r\n/**\r\n * Remove the repo and make sure it is disconnected.\r\n *\r\n */\r\nfunction repoManagerDeleteRepo(repo, appName) {\r\n const appRepos = repos[appName];\r\n // This should never happen...\r\n if (!appRepos || appRepos[repo.key] !== repo) {\r\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\r\n }\r\n repoInterrupt(repo);\r\n delete appRepos[repo.key];\r\n}\r\n/**\r\n * Ensures a repo doesn't already exist and then creates one using the\r\n * provided app.\r\n *\r\n * @param repoInfo - The metadata about the Repo\r\n * @returns The Repo object for the specified server / repoName.\r\n */\r\nfunction repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {\r\n let appRepos = repos[app.name];\r\n if (!appRepos) {\r\n appRepos = {};\r\n repos[app.name] = appRepos;\r\n }\r\n let repo = appRepos[repoInfo.toURLString()];\r\n if (repo) {\r\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\r\n }\r\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\r\n appRepos[repoInfo.toURLString()] = repo;\r\n return repo;\r\n}\r\n/**\r\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\r\n */\r\nfunction repoManagerForceRestClient(forceRestClient) {\r\n useRestClient = forceRestClient;\r\n}\r\n/**\r\n * Class representing a Firebase Realtime Database.\r\n */\r\nclass Database {\r\n /** @hideconstructor */\r\n constructor(_repoInternal, \r\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\r\n app) {\r\n this._repoInternal = _repoInternal;\r\n this.app = app;\r\n /** Represents a `Database` instance. */\r\n this['type'] = 'database';\r\n /** Track if the instance has been used (root or repo accessed) */\r\n this._instanceStarted = false;\r\n }\r\n get _repo() {\r\n if (!this._instanceStarted) {\r\n repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);\r\n this._instanceStarted = true;\r\n }\r\n return this._repoInternal;\r\n }\r\n get _root() {\r\n if (!this._rootInternal) {\r\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\r\n }\r\n return this._rootInternal;\r\n }\r\n _delete() {\r\n if (this._rootInternal !== null) {\r\n repoManagerDeleteRepo(this._repo, this.app.name);\r\n this._repoInternal = null;\r\n this._rootInternal = null;\r\n }\r\n return Promise.resolve();\r\n }\r\n _checkNotDeleted(apiName) {\r\n if (this._rootInternal === null) {\r\n fatal('Cannot call ' + apiName + ' on a deleted database.');\r\n }\r\n }\r\n}\r\nfunction checkTransportInit() {\r\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\r\n warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');\r\n }\r\n}\r\n/**\r\n * Force the use of websockets instead of longPolling.\r\n */\r\nfunction forceWebSockets() {\r\n checkTransportInit();\r\n BrowserPollConnection.forceDisallow();\r\n}\r\n/**\r\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\r\n */\r\nfunction forceLongPolling() {\r\n checkTransportInit();\r\n WebSocketConnection.forceDisallow();\r\n BrowserPollConnection.forceAllow();\r\n}\r\n/**\r\n * Returns the instance of the Realtime Database SDK that is associated with the provided\r\n * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if\r\n * no instance exists or if the existing instance uses a custom database URL.\r\n *\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\r\n * Database instance is associated with.\r\n * @param url - The URL of the Realtime Database instance to connect to. If not\r\n * provided, the SDK connects to the default instance of the Firebase App.\r\n * @returns The `Database` instance of the provided app.\r\n */\r\nfunction getDatabase(app = getApp(), url) {\r\n const db = _getProvider(app, 'database').getImmediate({\r\n identifier: url\r\n });\r\n if (!db._instanceStarted) {\r\n const emulator = getDefaultEmulatorHostnameAndPort('database');\r\n if (emulator) {\r\n connectDatabaseEmulator(db, ...emulator);\r\n }\r\n }\r\n return db;\r\n}\r\n/**\r\n * Modify the provided instance to communicate with the Realtime Database\r\n * emulator.\r\n *\r\n *

    Note: This method must be called before performing any other operation.\r\n *\r\n * @param db - The instance to modify.\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 8080)\r\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\r\n */\r\nfunction connectDatabaseEmulator(db, host, port, options = {}) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('useEmulator');\r\n if (db._instanceStarted) {\r\n fatal('Cannot call useEmulator() after instance has already been initialized.');\r\n }\r\n const repo = db._repoInternal;\r\n let tokenProvider = undefined;\r\n if (repo.repoInfo_.nodeAdmin) {\r\n if (options.mockUserToken) {\r\n fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".');\r\n }\r\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\r\n }\r\n else if (options.mockUserToken) {\r\n const token = typeof options.mockUserToken === 'string'\r\n ? options.mockUserToken\r\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\r\n tokenProvider = new EmulatorTokenProvider(token);\r\n }\r\n // Modify the repo to apply emulator settings\r\n repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\r\n}\r\n/**\r\n * Disconnects from the server (all Database operations will be completed\r\n * offline).\r\n *\r\n * The client automatically maintains a persistent connection to the Database\r\n * server, which will remain active indefinitely and reconnect when\r\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\r\n * to control the client connection in cases where a persistent connection is\r\n * undesirable.\r\n *\r\n * While offline, the client will no longer receive data updates from the\r\n * Database. However, all Database operations performed locally will continue to\r\n * immediately fire events, allowing your application to continue behaving\r\n * normally. Additionally, each operation performed locally will automatically\r\n * be queued and retried upon reconnection to the Database server.\r\n *\r\n * To reconnect to the Database and begin receiving remote events, see\r\n * `goOnline()`.\r\n *\r\n * @param db - The instance to disconnect.\r\n */\r\nfunction goOffline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOffline');\r\n repoInterrupt(db._repo);\r\n}\r\n/**\r\n * Reconnects to the server and synchronizes the offline Database state\r\n * with the server state.\r\n *\r\n * This method should be used after disabling the active connection with\r\n * `goOffline()`. Once reconnected, the client will transmit the proper data\r\n * and fire the appropriate events so that your client \"catches up\"\r\n * automatically.\r\n *\r\n * @param db - The instance to reconnect.\r\n */\r\nfunction goOnline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOnline');\r\n repoResume(db._repo);\r\n}\r\nfunction enableLogging(logger, persistent) {\r\n enableLogging$1(logger, persistent);\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 registerDatabase(variant) {\r\n setSDKVersion(SDK_VERSION$1);\r\n _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const authProvider = container.getProvider('auth-internal');\r\n const appCheckProvider = container.getProvider('app-check-internal');\r\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);\r\n }, \"PUBLIC\" /* ComponentType.PUBLIC */).setMultipleInstances(true));\r\n registerVersion(name, version, variant);\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 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 SERVER_TIMESTAMP = {\r\n '.sv': 'timestamp'\r\n};\r\n/**\r\n * Returns a placeholder value for auto-populating the current timestamp (time\r\n * since the Unix epoch, in milliseconds) as determined by the Firebase\r\n * servers.\r\n */\r\nfunction serverTimestamp() {\r\n return SERVER_TIMESTAMP;\r\n}\r\n/**\r\n * Returns a placeholder value that can be used to atomically increment the\r\n * current database value by the provided delta.\r\n *\r\n * @param delta - the amount to modify the current value atomically.\r\n * @returns A placeholder value for modifying data atomically server-side.\r\n */\r\nfunction increment(delta) {\r\n return {\r\n '.sv': {\r\n 'increment': delta\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 * A type for the resolve value of {@link runTransaction}.\r\n */\r\nclass TransactionResult {\r\n /** @hideconstructor */\r\n constructor(\r\n /** Whether the transaction was successfully committed. */\r\n committed, \r\n /** The resulting data snapshot. */\r\n snapshot) {\r\n this.committed = committed;\r\n this.snapshot = snapshot;\r\n }\r\n /** Returns a JSON-serializable representation of this object. */\r\n toJSON() {\r\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\r\n }\r\n}\r\n/**\r\n * Atomically modifies the data at this location.\r\n *\r\n * Atomically modify the data at this location. Unlike a normal `set()`, which\r\n * just overwrites the data regardless of its previous value, `runTransaction()` is\r\n * used to modify the existing value to a new value, ensuring there are no\r\n * conflicts with other clients writing to the same location at the same time.\r\n *\r\n * To accomplish this, you pass `runTransaction()` an update function which is\r\n * used to transform the current value into a new value. If another client\r\n * writes to the location before your new value is successfully written, your\r\n * update function will be called again with the new current value, and the\r\n * write will be retried. This will happen repeatedly until your write succeeds\r\n * without conflict or you abort the transaction by not returning a value from\r\n * your update function.\r\n *\r\n * Note: Modifying data with `set()` will cancel any pending transactions at\r\n * that location, so extreme care should be taken if mixing `set()` and\r\n * `runTransaction()` to update the same data.\r\n *\r\n * Note: When using transactions with Security and Firebase Rules in place, be\r\n * aware that a client needs `.read` access in addition to `.write` access in\r\n * order to perform a transaction. This is because the client-side nature of\r\n * transactions requires the client to read the data in order to transactionally\r\n * update it.\r\n *\r\n * @param ref - The location to atomically modify.\r\n * @param transactionUpdate - A developer-supplied function which will be passed\r\n * the current data stored at this location (as a JavaScript object). The\r\n * function should return the new value it would like written (as a JavaScript\r\n * object). If `undefined` is returned (i.e. you return with no arguments) the\r\n * transaction will be aborted and the data at this location will not be\r\n * modified.\r\n * @param options - An options object to configure transactions.\r\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\r\n * callback to handle success and failure.\r\n */\r\nfunction runTransaction(ref, \r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\ntransactionUpdate, options) {\r\n var _a;\r\n ref = getModularInstance(ref);\r\n validateWritablePath('Reference.transaction', ref._path);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');\r\n }\r\n const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;\r\n const deferred = new Deferred();\r\n const promiseComplete = (error, committed, node) => {\r\n let dataSnapshot = null;\r\n if (error) {\r\n deferred.reject(error);\r\n }\r\n else {\r\n dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);\r\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\r\n }\r\n };\r\n // Add a watch to make sure we get server updates.\r\n const unwatcher = onValue(ref, () => { });\r\n repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);\r\n return deferred.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\nPersistentConnection;\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\r\n this.sendRequest('q', { p: pathString }, onComplete);\r\n};\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.echo = function (data, onEcho) {\r\n this.sendRequest('echo', { d: data }, onEcho);\r\n};\r\n// RealTimeConnection properties that we use in tests.\r\nConnection;\r\n/**\r\n * @internal\r\n */\r\nconst hijackHash = function (newHash) {\r\n const oldPut = PersistentConnection.prototype.put;\r\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\r\n if (hash !== undefined) {\r\n hash = newHash();\r\n }\r\n oldPut.call(this, pathString, data, onComplete, hash);\r\n };\r\n return function () {\r\n PersistentConnection.prototype.put = oldPut;\r\n };\r\n};\r\nRepoInfo;\r\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n * @internal\r\n */\r\nconst forceRestClient = function (forceRestClient) {\r\n repoManagerForceRestClient(forceRestClient);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2023 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 * Used by console to create a database based on the app,\r\n * passed database URL and a custom auth implementation.\r\n * @internal\r\n * @param app - A valid FirebaseApp-like object\r\n * @param url - A valid Firebase databaseURL\r\n * @param version - custom version e.g. firebase-admin version\r\n * @param customAppCheckImpl - custom app check implementation\r\n * @param customAuthImpl - custom auth implementation\r\n */\r\nfunction _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {\r\n setSDKVersion(version);\r\n /**\r\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\r\n * any actual function.\r\n */\r\n const componentContainer = new ComponentContainer('database-standalone');\r\n const authProvider = new Provider('auth-internal', componentContainer);\r\n let appCheckProvider;\r\n if (customAppCheckImpl) {\r\n appCheckProvider = new Provider('app-check-internal', componentContainer);\r\n appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n }\r\n authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);\r\n}\n\n/**\r\n * Firebase Realtime Database\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterDatabase();\n\nexport { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, _initStandalone, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };\n//# sourceMappingURL=index.esm2017.js.map\n"],"names":["CONSTANTS","assert","assertion","message","assertionError","stringToByteArray$1","str","out","p","c","byteArrayToString","bytes","pos","c1","c2","c3","c4","u","base64","input","webSafe","byteToCharMap","output","i","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","charToByteMap","byte4","DecodeBase64StringError","base64Encode","utf8Bytes","base64urlEncodeWithoutPadding","base64Decode","deepCopy","value","deepExtend","target","source","dateValue","prop","isValidKey","key","getGlobal","getDefaultsFromGlobal","getDefaultsFromEnvVariable","define_process_env_default","defaultsJsonString","getDefaultsFromCookie","match","decoded","getDefaults","e","getDefaultEmulatorHost","productName","_a","_b","getDefaultEmulatorHostnameAndPort","host","separatorIndex","port","getDefaultAppConfig","getExperimentalSetting","name","Deferred","resolve","reject","callback","error","createMockUserToken","token","projectId","header","project","iat","sub","payload","getUA","isMobileCordova","isNode","forceEnvironment","isCloudflareWorker","isBrowserExtension","runtime","isReactNative","isIE","ua","isNodeSdk","isSafari","isIndexedDBAvailable","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","request","areCookiesEnabled","ERROR_NAME","FirebaseError","code","customData","ErrorFactory","service","serviceName","errors","data","fullCode","template","replaceTemplate","fullMessage","PATTERN","_","jsonEval","stringify","decode","claims","signature","parts","isValidFormat","isAdmin","contains","obj","safeGet","isEmpty","map","fn","contextObj","res","deepEqual","a","b","aKeys","bKeys","k","aProp","bProp","isObject","thing","querystring","querystringParams","params","arrayVal","Sha1","buf","offset","W","t","d","f","length","lengthMinusBlock","n","inbuf","digest","totalBits","j","createSubscribe","executor","onNoObservers","proxy","ObserverProxy","observer","nextOrObserver","complete","implementsAnyMethods","noop","unsub","err","methods","method","errorPrefix","fnName","argName","stringToByteArray","high","low","stringLength","getModularInstance","Component","instanceFactory","type","mode","multipleInstances","props","DEFAULT_ENTRY_NAME","Provider","container","identifier","normalizedIdentifier","deferred","instance","options","optional","component","isComponentEager","instanceIdentifier","instanceDeferred","services","opts","normalizedDeferredIdentifier","existingCallbacks","existingInstance","callbacks","normalizeIdentifierForFactory","ComponentContainer","provider","LogLevel","levelStringToEnum","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","now","Logger","val","instanceOfAny","object","constructors","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","getCursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","promisifyRequest","promise","unlisten","success","wrap","cacheDonePromiseForTransaction","tx","done","idbProxyTraps","receiver","replaceTraps","wrapFunction","func","storeNames","unwrap","transformCachableValue","newValue","openDB","version","blocked","upgrade","blocking","terminated","openPromise","event","db","deleteDB","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","oldTraps","PlatformLoggerServiceImpl","isVersionServiceProvider","logString","name$q","version$1","logger","name$p","name$o","name$n","name$m","name$l","name$k","name$j","name$i","name$h","name$g","name$f","name$e","name$d","name$c","name$b","name$a","name$9","name$8","name$7","name$6","name$5","name$4","name$3","name$2","name$1","PLATFORM_LOG_STRING","_apps","_serverApps","_components","_addComponent","app","_registerComponent","componentName","serverApp","_getProvider","heartbeatController","_isFirebaseServerApp","ERRORS","ERROR_FACTORY","FirebaseAppImpl","config","SDK_VERSION","initializeApp","_options","rawConfig","existingApp","newApp","getApp","registerVersion","libraryKeyOrName","variant","library","libraryMismatch","versionMismatch","warning","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","oldVersion","readHeartbeatsFromIndexedDB","result","computeKey","idbGetError","writeHeartbeatsToIndexedDB","heartbeatObject","MAX_HEADER_BYTES","STORED_HEARTBEAT_RETENTION_MAX_MILLIS","HeartbeatServiceImpl","HeartbeatStorageImpl","agent","date","getUTCDateString","singleDateHeartbeat","hbTimestamp","heartbeatsToSend","unsentEntries","extractHeartbeatsForHeader","headerString","heartbeatsCache","maxSize","heartbeatEntry","hb","countBytes","idbHeartbeatObject","heartbeatsObject","existingHeartbeatsObject","registerCoreComponents","commonjsGlobal","Integer","Md5","h","g","r","l","m","q","v","w","x","y","z","A","B","C","D","F","E","G","I","J","XhrIo","WebChannel","EventType","ErrorCode","Stat","Event","getStatEventTarget","createWebChannelTransport","aa","ba","ca","da","ea","fa","ha","ia","ja","ka","la","ma","na","oa","pa","qa","ra","sa","ta","va","wa","xa","za","Aa","Ba","Ca","Ea","Da","Fa","Ga","Ha","Ia","Ja","Ka","La","Ma","Na","Oa","Qa","Sa","Ta","Ua","Va","Wa","Xa","Ya","Za","$a","ab","bb","cb","eb","fb","gb","ib","jb","kb","lb","mb","H","nb","ob","pb","qb","rb","sb","K","tb","ub","vb","wb","xb","L","yb","zb","Ab","Bb","Cb","Db","M","Eb","Fb","Gb","Hb","Ib","N","Jb","Kb","Lb","Mb","P","O","Nb","Ob","Pb","Q","Qb","Rb","Sb","Tb","Ub","Vb","Wb","Xb","Yb","Zb","$b","ac","R","ya","bc","S","cc","dc","fc","gc","hc","ic","jc","kc","lc","mc","nc","oc","pc","T","qc","rc","sc","tc","uc","vc","wc","xc","yc","zc","Ac","Bc","Cc","U","V","Dc","Ec","Fc","Gc","Hc","Ic","Jc","Kc","Lc","Mc","Oc","Pc","X","Qc","Rc","Sc","Tc","Uc","Vc","Wc","Xc","Yc","Zc","$c","ad","bd","cd","dd","ed","ec","fd","gd","hd","Y","Z","id","jd","User","__PRIVATE_getLogLevel","__PRIVATE_logDebug","__PRIVATE_argToString","__PRIVATE_logError","__PRIVATE_logWarn","fail","__PRIVATE_hardAssert","__PRIVATE_debugCast","FirestoreError","__PRIVATE_Deferred","__PRIVATE_OAuthToken","__PRIVATE_EmptyAuthCredentialsProvider","__PRIVATE_EmulatorAuthCredentialsProvider","__PRIVATE_FirebaseAuthCredentialsProvider","__PRIVATE_guardedChangeListener","__PRIVATE_awaitNextToken","__PRIVATE_registerAuth","__PRIVATE_FirstPartyToken","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","__PRIVATE_FirebaseAppCheckTokenProvider","onTokenChanged","__PRIVATE_registerAppCheck","__PRIVATE_randomBytes","__PRIVATE_AutoId","__PRIVATE_primitiveComparator","__PRIVATE_arrayEquals","Timestamp","SnapshotVersion","BasePath","ResourcePath","FieldPath$1","__PRIVATE_addCurrentSegment","DocumentKey","__PRIVATE_newIndexOffsetSuccessorFromReadTime","IndexOffset","__PRIVATE_newIndexOffsetFromDocument","__PRIVATE_indexOffsetComparator","PersistenceTransaction","__PRIVATE_ignoreIfPrimaryLeaseLoss","PersistencePromise","s","o","process","__PRIVATE_getAndroidVersion","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_ListenSequence","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","isSafeInteger","__PRIVATE_objectSize","forEach","__PRIVATE_mapToArray","SortedMap$1","SortedMap","LLRBNode","SortedMapIterator","SortedMapIterator$1","LLRBNode$1","SortedSet","SortedSetIterator","FieldMask","__PRIVATE_Base64DecodeError","ByteString","ne","__PRIVATE_normalizeTimestamp","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","__PRIVATE_isServerTimestamp","__PRIVATE_getPreviousValue","__PRIVATE_getLocalWriteTime","DatabaseInfo","DatabaseId","re","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_arrayValueContains","__PRIVATE_valueCompare","__PRIVATE_compareTimestamps","__PRIVATE_compareArrays","canonicalId","__PRIVATE_canonifyValue","__PRIVATE_refValue","isInteger","isArray","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","ObjectValue","__PRIVATE_extractFieldMask","MutableDocument","Bound","__PRIVATE_boundCompareToDocument","__PRIVATE_boundEquals","OrderBy","__PRIVATE_orderByEquals","Filter","FieldFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","CompositeFilter","__PRIVATE_compositeFilterIsConjunction","__PRIVATE_compositeFilterIsFlatConjunction","__PRIVATE_compositeFilterIsFlat","__PRIVATE_canonifyFilter","__PRIVATE_filterEquals","__PRIVATE_stringifyFilter","__PRIVATE_extractDocumentKeysFromArrayValue","__PRIVATE_TargetImpl","__PRIVATE_newTarget","__PRIVATE_canonifyTarget","__PRIVATE_targetEquals","__PRIVATE_targetIsDocumentTarget","__PRIVATE_QueryImpl","__PRIVATE_newQuery","__PRIVATE_newQueryForPath","__PRIVATE_queryMatchesAllDocuments","__PRIVATE_isCollectionGroupQuery","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_queryToAggregateTarget","__PRIVATE_queryWithAddedFilter","__PRIVATE_queryWithLimit","__PRIVATE_queryEquals","__PRIVATE_canonifyQuery","__PRIVATE_stringifyQuery","__PRIVATE_queryMatches","__PRIVATE_queryCollectionGroup","__PRIVATE_newQueryComparator","__PRIVATE_compareDocs","ObjectMap","oe","__PRIVATE_mutableDocumentMap","_e","documentMap","__PRIVATE_convertOverlayedDocumentMapToDocumentMap","__PRIVATE_newOverlayMap","__PRIVATE_newDocumentKeyMap","__PRIVATE_newMutationMap","ae","ue","__PRIVATE_documentKeySet","ce","__PRIVATE_targetIdSet","__PRIVATE_toDouble","__PRIVATE_toInteger","toNumber","TransformOperation","__PRIVATE_applyTransformOperationToLocalView","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_applyArrayUnionTransformOperation","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_applyArrayRemoveTransformOperation","__PRIVATE_computeTransformOperationBaseValue","asNumber","__PRIVATE_applyTransformOperationToRemoteDocument","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_coercedFieldValuesArray","FieldTransform","__PRIVATE_fieldTransformEquals","MutationResult","Precondition","__PRIVATE_preconditionIsValidForDocument","Mutation","__PRIVATE_calculateOverlayMutation","__PRIVATE_DeleteMutation","__PRIVATE_SetMutation","__PRIVATE_PatchMutation","__PRIVATE_mutationApplyToRemoteDocument","__PRIVATE_serverTransformResults","__PRIVATE_getPatch","__PRIVATE_mutationApplyToLocalView","__PRIVATE_localTransformResults","__PRIVATE_mutationExtractBaseValue","__PRIVATE_mutationEquals","__PRIVATE_VerifyMutation","MutationBatch","MutationBatchResult","Overlay","__PRIVATE_AggregateImpl","ExistenceFilter","le","he","__PRIVATE_isPermanentError","__PRIVATE_mapCodeFromRpcCode","__PRIVATE_newTextEncoder","Ie","__PRIVATE_getMd5HashValue","__PRIVATE_get64BitUints","BloomFilter","__PRIVATE_BloomFilterError","RemoteEvent","TargetChange","__PRIVATE_DocumentWatchChange","__PRIVATE_ExistenceFilterChange","__PRIVATE_WatchTargetChange","__PRIVATE_TargetState","__PRIVATE_snapshotChangesMap","__PRIVATE_WatchChangeAggregator","__PRIVATE_documentTargetMap","Te","Ee","de","JsonProtoSerializer","__PRIVATE_toInt32Proto","toTimestamp","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_toName","fromName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_toQueryPath","__PRIVATE_fromQueryPath","__PRIVATE_getEncodedDatabaseId","__PRIVATE_toMutationDocument","__PRIVATE_fromWatchChange","toMutation","__PRIVATE_toDocumentMask","__PRIVATE_fromWriteResults","__PRIVATE_toDocumentsTarget","__PRIVATE_toQueryTarget","__PRIVATE_toFilter","__PRIVATE_toFieldPathReference","__PRIVATE_toDirection","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_convertQueryTargetToQuery","__PRIVATE_fromFilter","__PRIVATE_fromFieldPathReference","__PRIVATE_toListenRequestLabels","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","TargetData","__PRIVATE_LocalSerializer","__PRIVATE_fromBundledQuery","__PRIVATE_MemoryIndexManager","__PRIVATE_MemoryCollectionParentIndex","__PRIVATE_TargetIdGenerator","RemoteDocumentChangeBuffer","OverlayedDocument","LocalDocumentsView","__PRIVATE_MemoryBundleCache","__PRIVATE_MemoryDocumentOverlayCache","__PRIVATE_MemoryGlobalsCache","__PRIVATE_ReferenceSet","__PRIVATE_DocReference","__PRIVATE_MemoryMutationQueue","__PRIVATE_MemoryRemoteDocumentCacheImpl","__PRIVATE_MemoryRemoteDocumentChangeBuffer","__PRIVATE_MemoryTargetCache","__PRIVATE_MemoryPersistence","__PRIVATE_MemoryTransaction","__PRIVATE_MemoryEagerDelegate","__PRIVATE_LocalViewChanges","QueryContext","__PRIVATE_QueryEngine","__PRIVATE_LocalStoreImpl","__PRIVATE_newLocalStore","__PRIVATE_localStoreHandleUserChange","__PRIVATE_localStoreAcknowledgeBatch","__PRIVATE_localStoreGetLastRemoteSnapshotVersion","__PRIVATE_localStoreApplyRemoteEventToLocalCache","__PRIVATE_populateDocumentChangeBuffer","__PRIVATE_localStoreGetNextMutationBatch","__PRIVATE_localStoreAllocateTarget","__PRIVATE_localStoreReleaseTarget","__PRIVATE_localStoreExecuteQuery","__PRIVATE_setMaxReadTime","__PRIVATE_LocalClientState","__PRIVATE_MemorySharedClientState","__PRIVATE_NoopConnectivityMonitor","__PRIVATE_BrowserConnectivityMonitor","me","__PRIVATE_generateUniqueDebugId","fe","__PRIVATE_StreamBridge","ge","__PRIVATE_WebChannelConnection","__PRIVATE_unguardedEventListen","getDocument","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_PersistentStream","__PRIVATE_PersistentListenStream","__PRIVATE_PersistentWriteStream","__PRIVATE_DatastoreImpl","__PRIVATE_OnlineStateTracker","__PRIVATE_RemoteStoreImpl","__PRIVATE_canUseNetwork","__PRIVATE_disableNetworkInternal","__PRIVATE_enableNetworkInternal","__PRIVATE_remoteStoreListen","__PRIVATE_shouldStartWatchStream","__PRIVATE_startWatchStream","__PRIVATE_ensureWatchStream","__PRIVATE_sendWatchRequest","__PRIVATE_remoteStoreUnlisten","__PRIVATE_sendUnwatchRequest","__PRIVATE_cleanUpWatchStreamState","__PRIVATE_onWatchStreamConnected","__PRIVATE_onWatchStreamOpen","__PRIVATE_onWatchStreamClose","__PRIVATE_onWatchStreamChange","__PRIVATE_disableNetworkUntilRecovery","__PRIVATE_executeWithRecovery","__PRIVATE_fillWritePipeline","__PRIVATE_ensureWriteStream","__PRIVATE_canAddToWritePipeline","__PRIVATE_addToWritePipeline","__PRIVATE_shouldStartWriteStream","__PRIVATE_startWriteStream","__PRIVATE_onWriteStreamOpen","__PRIVATE_onWriteHandshakeComplete","__PRIVATE_onMutationResult","__PRIVATE_onWriteStreamClose","__PRIVATE_remoteStoreHandleCredentialChange","__PRIVATE_remoteStoreApplyPrimaryState","DelayedOperation","__PRIVATE_wrapInUserErrorIfRecoverable","DocumentSet","__PRIVATE_DocumentChangeSet","ViewSnapshot","__PRIVATE_QueryListenersInfo","__PRIVATE_EventManagerImpl","__PRIVATE_newQueriesObjectMap","__PRIVATE_eventManagerListen","__PRIVATE_raiseSnapshotsInSyncEvent","__PRIVATE_eventManagerUnlisten","__PRIVATE_eventManagerOnWatchChange","__PRIVATE_eventManagerOnWatchError","pe","ye","__PRIVATE_QueryListener","__PRIVATE_AddedLimboDocument","__PRIVATE_RemovedLimboDocument","__PRIVATE_View","order","__PRIVATE_QueryView","LimboResolution","__PRIVATE_SyncEngineImpl","__PRIVATE_syncEngineListen","__PRIVATE_ensureWatchCallbacks","__PRIVATE_allocateTargetAndMaybeListen","__PRIVATE_triggerRemoteStoreListen","__PRIVATE_initializeViewAndComputeSnapshot","__PRIVATE_updateTrackedLimbos","__PRIVATE_syncEngineUnlisten","__PRIVATE_removeAndCleanupTarget","__PRIVATE_triggerRemoteStoreUnlisten","__PRIVATE_syncEngineWrite","__PRIVATE_syncEngineEnsureWriteCallbacks","__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore","__PRIVATE_syncEngineApplyRemoteEvent","__PRIVATE_syncEngineApplyOnlineStateChange","__PRIVATE_syncEngineRejectListen","__PRIVATE_pumpEnqueuedLimboResolutions","__PRIVATE_syncEngineApplySuccessfulWrite","__PRIVATE_processUserCallback","__PRIVATE_triggerPendingWritesCallbacks","__PRIVATE_syncEngineRejectFailedWrite","__PRIVATE_removeLimboTarget","__PRIVATE_trackLimboChange","__PRIVATE_syncEngineHandleCredentialChange","__PRIVATE_syncEngineGetRemoteKeysForTarget","__PRIVATE_MemoryOfflineComponentProvider","OnlineComponentProvider","__PRIVATE_AsyncObserver","FirestoreClient","__PRIVATE_setOfflineComponentProvider","__PRIVATE_setOnlineComponentProvider","__PRIVATE_ensureOfflineComponents","__PRIVATE_ensureOnlineComponents","__PRIVATE_getSyncEngine","__PRIVATE_getDatastore","__PRIVATE_getEventManager","__PRIVATE_firestoreClientGetDocumentViaSnapshotListener","__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener","__PRIVATE_firestoreClientRunAggregateQuery","__PRIVATE_cloneLongPollingOptions","we","__PRIVATE_validateNonEmptyArgument","__PRIVATE_validateIsNotUsedTogether","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_valueDescription","__PRIVATE_cast","__PRIVATE_validatePositiveNumber","FirestoreSettingsImpl","Firestore$1","connectFirestoreEmulator","Query","DocumentReference","CollectionReference","collection","doc","__PRIVATE_AsyncQueueImpl","__PRIVATE_isPartialObserver","Firestore","getFirestore","ensureFirestoreConfigured","__PRIVATE_configureFirestore","AggregateField","AggregateQuerySnapshot","Bytes","FieldPath","FieldValue","GeoPoint","VectorValue","be","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_ParseContextImpl","__PRIVATE_createError","__PRIVATE_UserDataReader","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_validatePlainObject","__PRIVATE_parseObject","__PRIVATE_fieldPathFromArgument$1","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE_parseData","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_parseUpdateData","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_parseUpdateVarargs","__PRIVATE_parseQueryValue","__PRIVATE_looksLikeJsonObject","De","DocumentSnapshot$1","QueryDocumentSnapshot$1","__PRIVATE_fieldPathFromArgument","__PRIVATE_validateHasExplicitOrderByForLimitToLast","AppliableConstraint","QueryConstraint","query","QueryCompositeFilterConstraint","QueryFieldFilterConstraint","__PRIVATE_validateNewFieldFilter","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_parseDocumentIdValue","where","QueryOrderByConstraint","orderBy","QueryLimitConstraint","limit","AbstractUserDataWriter","__PRIVATE_applyFirestoreDataConverter","count","SnapshotMetadata","DocumentSnapshot","QueryDocumentSnapshot","QuerySnapshot","__PRIVATE_resultChangeType","getDoc","__PRIVATE_convertToDocSnapshot","__PRIVATE_ExpUserDataWriter","getDocs","setDoc","executeWrite","updateDoc","deleteDoc","onSnapshot","getCountFromServer","getAggregateFromServer","WriteBatch","__PRIVATE_validateReference","serverTimestamp","arrayUnion","arrayRemove","writeBatch","extendStatics","__extends","__","__assign","__rest","_prodErrorMap","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logWarn","msg","_logError","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","_serverAppCurrentUserOperationNotSupportedError","fullParams","_assert","debugFail","failure","debugAssert","_getCurrentUrl","_isHttpOrHttps","_getCurrentScheme","_isOnline","_getUserLanguage","navigatorLanguage","Delay","shortDelay","longDelay","_emulatorUrl","path","url","FetchProvider","fetchImpl","headersImpl","responseImpl","SERVER_ERROR_MAP","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","body","headers","fetchArgs","_getFinalTarget","fetchFn","networkTimeout","NetworkTimeout","response","json","_makeTaggedError","errorMessage","serverErrorCode","serverErrorMessage","authError","_performSignInRequest","serverResponse","base","errorParams","deleteAccount","getAccountInfo","utcTimestampToDateString","utcTimestamp","getIdTokenResult","user","forceRefresh","userInternal","_parseToken","firebase","signInProvider","secondsStringToMilliseconds","seconds","algorithm","_tokenExpiresIn","parsedToken","_logoutIfInvalidated","bypassAuthState","isUserInvalidated","ProactiveRefresh","wasError","interval","UserMetadata","createdAt","lastLoginAt","metadata","_reloadWithoutSaving","idToken","coreAccount","newProviderData","extractProviderData","providerData","mergeProviderData","oldIsAnonymous","newIsAnonymous","isAnonymous","updates","reload","original","newData","providers","providerId","requestStsToken","refreshToken","tokenApiHost","apiKey","revokeToken","StsTokenManager","expiresIn","oldToken","accessToken","expiresInSec","appName","expirationTime","manager","stsTokenManager","assertStringOrUndefined","UserImpl","uid","opt","userInfo","newUser","tokensRefreshed","_c","_d","_f","_g","_h","displayName","email","phoneNumber","photoURL","tenantId","_redirectEventId","emailVerified","plainObjectTokenManager","idTokenResponse","instanceCache","_getInstance","cls","InMemoryPersistence","_key","_listener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","blob","newPersistence","currentUser","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_getBrowserName","userAgent","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","matches","_isIOS","_isIOSStandalone","_isIE10","_isMobileBrowser","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","AuthMiddlewareQueue","onAbort","wrappedCallback","index","nextUser","onAbortStack","beforeStateCallback","_getPasswordPolicy","MINIMUM_MIN_PASSWORD_LENGTH","PasswordPolicyImpl","responseOptions","password","status","minPasswordLength","maxPasswordLength","passwordChar","containsLowercaseCharacter","containsUppercaseCharacter","containsNumericCharacter","containsNonAlphanumericCharacter","AuthImpl","heartbeatServiceProvider","appCheckServiceProvider","Subscription","popupRedirectResolver","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","redirectUserEventId","storedUserEventId","redirectResolver","userExtern","skipBeforeStateCallbacks","passwordPolicy","completed","unsubscribe","redirectManager","resolver","currentUid","subscription","isUnsubscribed","action","framework","heartbeatsHeader","appCheckToken","appCheckTokenResult","_castAuth","externalJSProvider","_setExternalJSProvider","_loadJS","_gapiScriptUrl","_generateCallbackName","prefix","initializeAuth","deps","initialOptions","_initializeAuthInstance","hierarchy","connectAuthEmulator","authInternal","disableWarnings","protocol","extractProtocol","extractHostAndPort","portStr","emitEmulatorWarning","protocolEnd","authority","hostAndPort","bracketedIPv6","parsePort","attachBanner","el","sty","AuthCredential","signInMethod","_auth","_idToken","signInWithIdp","IDP_REQUEST_URI$1","OAuthCredential","cred","postBody","FederatedAuthProvider","languageCode","customOAuthParameters","BaseOAuthProvider","scope","FacebookAuthProvider","userCredential","tokenResponse","GoogleAuthProvider","oauthIdToken","oauthAccessToken","GithubAuthProvider","TwitterAuthProvider","secret","oauthTokenSecret","UserCredentialImpl","operationType","providerIdForResponse","MultiFactorError","_processCredentialSavingMfaContextIfNecessary","credential","_link$1","_reauthenticate","parsed","localId","_signInWithCredential","signInWithCustomToken$1","signInWithCustomToken","customToken","onIdTokenChanged","beforeAuthStateChanged","onAuthStateChanged","signOut","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","_POLLING_INTERVAL_MS$1","IE10_LOCAL_STORAGE_SYNC_DELAY","BrowserLocalPersistence","poll","oldValue","_oldValue","triggerListeners","storedValue","listeners","listener","browserLocalPersistence","BrowserSessionPersistence","browserSessionPersistence","_allSettled","promises","reason","Receiver","eventTarget","newInstance","messageEvent","eventId","eventType","handlers","handler","eventHandler","_generateEventId","digits","random","Sender","timeout","messageChannel","completionTimer","ackTimer","_window","_setWindowLocation","_isWorker","_getActiveServiceWorker","_getServiceWorkerController","_getWorkerGlobalScope","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","getObjectStore","isReadWrite","_deleteDatabase","_openDatabase","_putObject","getObject","_deleteObject","_POLLING_INTERVAL_MS","_TRANSACTION_RETRY_COUNT","IndexedDBLocalPersistence","op","numAttempts","_origin","_data","results","write","getAllRequest","keys","keysInResult","localKey","indexedDBLocalPersistence","_withDefaultResolver","resolverOverride","IdpCredential","_signIn","_reauth","_link","AbstractPopupRedirectOperation","filter","urlResponse","sessionId","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","isSupported","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","_getAndClearPendingRedirectStatus","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_overrideRedirectResult","_getRedirectResult","resolverExtern","EVENT_DUPLICATION_CACHE_DURATION_MS","AuthEventManager","authEventConsumer","handled","consumer","isRedirectEvent","isNullRedirectEvent","eventIdMatches","eventUid","_getProjectConfig","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","domain","matchDomain","expected","currentUrl","hostname","ceUrl","escapedDomainPattern","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","hint","loadGapi","loadGapiIframe","cbName","cachedGApiLoader","_loadGapi","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","EID_FROM_APIHOST","getIframeUrl","eid","_openIframe","context","gapi","iframe","networkError","networkErrorTimer","clearTimerAndResolve","BASE_POPUP_OPTIONS","DEFAULT_WIDTH","DEFAULT_HEIGHT","TARGET_BLANK","FIREFOX_EMPTY_URL","AuthPopup","window","_open","width","height","top","left","optionsString","accum","openAsNewWindowIOS","newWin","click","WIDGET_PATH","EMULATOR_WIDGET_PATH","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","scopes","paramsDict","appCheckTokenFragment","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","BrowserPopupRedirectResolver","iframeEvent","browserPopupRedirectResolver","AuthInterop","getVersionForPlatform","registerAuth","authDomain","authInstance","_instanceIdentifier","_instance","DEFAULT_ID_TOKEN_MAX_AGE","authIdTokenMaxAge","lastPostedIdToken","mintCookieFactory","idTokenResult","idTokenAge","getAuth","authTokenSyncPath","authTokenSyncUrl","mintCookie","authEmulatorHost","getScriptParentElement","setSDKVersion","DOMStorageWrapper","domStorage_","storedVal","MemoryStorage","createStoragefor","domStorageName","domStorage","PersistentStorage","SessionStorage","LUIDGenerator","sha1","sha1Bytes","buildLogMessage_","varArgs","arg","firstLog_","enableLogging$1","logger_","persistent","log","logWrapper","fatal","warn","warnIfPageIsSecure","isInvalidJSONNumber","executeWhenDOMReady","called","wrappedFn","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","len","dataSegs","each","doubleToIEEE754String","ebits","fbits","bias","ln","bits","hexByteString","hexByte","isChromeExtensionContentScript","isWindowsStoreApp","INTEGER_REGEXP_","INTEGER_32_MIN","INTEGER_32_MAX","intVal","exceptionGuard","stack","beingCrawled","setTimeoutNonBlocking","time","AppCheckTokenProvider","appName_","appCheckProvider","appCheck","FirebaseAuthTokenProvider","firebaseOptions_","authProvider_","EmulatorTokenProvider","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN_RE","LAST_SESSION_PARAM","APPLICATION_ID_PARAM","APP_CHECK_TOKEN_PARAM","WEBSOCKET","LONG_POLLING","RepoInfo","secure","namespace","webSocketOnly","nodeAdmin","persistenceKey","includeNamespaceInQueryParams","isUsingEmulator","newHost","repoInfoNeedsQueryParam","repoInfo","repoInfoConnectionURL","connURL","pairs","StatsCollection","amount","collections","reporters","statsManagerGetCollection","hashString","statsManagerGetOrCreateReporter","creatorFunction","PacketReceiver","onMessage_","responseNum","requestNum","toProcess","FIREBASE_LONGPOLL_START_PARAM","FIREBASE_LONGPOLL_CLOSE_COMMAND","FIREBASE_LONGPOLL_COMMAND_CB_NAME","FIREBASE_LONGPOLL_DATA_CB_NAME","FIREBASE_LONGPOLL_ID_PARAM","FIREBASE_LONGPOLL_PW_PARAM","FIREBASE_LONGPOLL_SERIAL_PARAM","FIREBASE_LONGPOLL_CALLBACK_ID_PARAM","FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM","FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET","FIREBASE_LONGPOLL_DATA_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM","MAX_URL_DATA_SIZE","SEG_HEADER_SIZE","MAX_PAYLOAD_SIZE","KEEPALIVE_REQUEST_INTERVAL","LP_CONNECT_TIMEOUT","BrowserPollConnection","connId","applicationId","authToken","transportSessionId","lastSessionId","onMessage","onDisconnect","FirebaseIFrameScriptHolder","command","arg1","arg2","arg3","arg4","pN","urlParams","connectURL","dataStr","base64data","pw","bytesReceived","commandCB","onMessageCB","urlFn","script","iframeContents","theURL","curDataString","theSeg","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","newScript","rstate","WEBSOCKET_MAX_FRAME_SIZE","WEBSOCKET_KEEPALIVE_INTERVAL","WebSocketImpl","WebSocketConnection","isOldAndroid","oldAndroidRegex","oldAndroidMatch","fullMess","jsonMess","frameCount","mess","remainingData","TransportManager","isWebSocketsAvailable","isSkipPollConnection","transports","transport","UPGRADE_TIMEOUT","DELAY_BEFORE_SENDING_EXTRA_REQUESTS","BYTES_SENT_HEALTHY_OVERRIDE","BYTES_RECEIVED_HEALTHY_OVERRIDE","MESSAGE_TYPE","MESSAGE_DATA","CONTROL_SHUTDOWN","CONTROL_RESET","CONTROL_ERROR","CONTROL_PONG","SWITCH_ACK","END_TRANSMISSION","PING","SERVER_HELLO","Connection","repoInfo_","applicationId_","appCheckToken_","authToken_","onReady_","onDisconnect_","onKill_","conn","onMessageReceived","onConnectionLost","healthyTimeoutMS","everConnected","dataMsg","controlData","cmd","parsedData","layer","handshakePayload","handshake","timestamp","ServerActions","pathString","onComplete","hash","stats","EventEmitter","allowedEvents_","eventData","et","OnlineMonitor","MAX_PATH_DEPTH","MAX_PATH_LENGTH_BYTES","Path","pathOrString","pieceNum","copyTo","newEmptyPath","pathGetFront","pathGetLength","pathPopFront","pathGetBack","pathToUrlEncodedString","pathSlice","begin","pathParent","pieces","pathChild","childPathObj","childPieces","pathIsEmpty","newRelativePath","outerPath","innerPath","outer","inner","pathEquals","other","pathContains","ValidationPath","errorPrefix_","validationPathCheckValid","validationPathPush","validationPath","child","validationPathPop","last","validationPathToErrorString","VisibilityMonitor","hidden","visibilityChange","visible","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","RECONNECT_MAX_DELAY_FOR_ADMINS","RECONNECT_DELAY_MULTIPLIER","RECONNECT_DELAY_RESET_TIMEOUT","SERVER_KILL_INTERRUPT_REASON","INVALID_TOKEN_THRESHOLD","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","appCheckTokenProvider_","authOverride_","onResponse","curReqNum","outstandingGet","currentHashFn","tag","queryId","listenSpec","get","req","warnings","indexSpec","indexPath","authMethod","requestData","queryObj","errorReason","reqNum","online","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage","onReady","canceled","connection","closeFn","sendRequestFn","delta","put","listen","normalizedPathString","statusCode","explanation","queries","clientName","NamedNode","node","Index","oldNode","newNode","oldWrapped","newWrapped","__EMPTY_NODE","KeyIndex","indexValue","KEY_INDEX","startKey","comparator","isReverse_","resultGenerator_","cmp","color","right","smallest","nl","nr","blackDepth","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","MAX_NODE$2","setMaxNode$1","priorityHashText","priority","validatePriorityNode","priorityNode","__childrenNodeConstructor","LeafNode","value_","priorityNode_","newPriorityNode","childName","childNode","newChildNode","front","exportFormat","toHash","otherLeaf","otherLeafType","thisLeafType","otherIndex","thisIndex","nodeFromJSON$1","MAX_NODE$1","setNodeFromJSON","setMaxNode","PriorityIndex","aPriority","bPriority","indexCmp","PRIORITY_INDEX","LOG_2","Base12Num","logBase2","num","bitMask","mask","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","namedNode","middle","buildFrom12Array","base12","root","buildPennant","chunkSize","childTree","attachPennant","pennant","isOne","_defaultIndexMap","fallbackObject","IndexMap","indexes_","indexSet_","indexKey","sortedMap","indexDefinition","existingChildren","sawIndexedValue","iter","next","newIndex","indexName","newIndexSet","newIndexes","indexedChildren","existingSnap","newChildren","EMPTY_NODE","ChildrenNode","children_","indexMap_","newIndexMap","newPriority","newImmediateChild","numKeys","maxKey","allIntegerKeys","array","childHash","idx","predecessor","minKey","wrappedNode","startPost","iterator","endPost","MAX_NODE","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","USE_HINZE","nodeFromJSON","jsonLeaf","children","childrenHavePriority","childSet","sortedChildSet","childData","PathIndex","indexPath_","snap","aChild","bChild","valueNode","ValueIndex","VALUE_INDEX","changeValue","snapshotNode","changeChildAdded","changeChildRemoved","changeChildChanged","oldSnap","changeChildMoved","QueryParams","copy","queryParamsToRestQueryStringParameters","queryParams","qs","startParam","endParam","queryParamsGetQueryObject","viewFrom","ReadonlyRestClient","listenId","thisListen","queryStringParameters","xhr","SnapshotHolder","newSnapshotNode","newSparseSnapshotTree","sparseSnapshotTreeRemember","sparseSnapshotTree","childKey","sparseSnapshotTreeForEachTree","prefixPath","sparseSnapshotTreeForEachChild","tree","StatsListener","collection_","newStats","stat","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","REPORT_STATS_INTERVAL","StatsReporter","server_","reportedStats","haveStatsToReport","OperationType","newOperationSourceUser","newOperationSourceServer","newOperationSourceServerTaggedQuery","AckUserWrite","affectedTree","revert","Overwrite","Merge","CacheNode","node_","fullyInitialized_","filtered_","eventGeneratorGenerateEventsForChanges","eventGenerator","changes","eventCache","eventRegistrations","events","moves","change","eventGeneratorGenerateEventsForType","registrations","filteredChanges","eventGeneratorCompareChanges","materializedChange","eventGeneratorMaterializeSingleChange","registration","aWrapped","bWrapped","newViewCache","serverCache","viewCacheUpdateEventSnap","viewCache","eventSnap","filtered","viewCacheUpdateServerSnap","serverSnap","viewCacheGetCompleteEventSnap","viewCacheGetCompleteServerSnap","emptyChildrenSingleton","EmptyChildren","ImmutableTree","childPath","childSnap","relativePath","predicate","childExistingPathAndValue","toSet","newChild","newTree","pathSoFar","pathToFollow","nextChild","currentRelativePath","CompoundWrite","writeTree_","compoundWriteAddWrite","compoundWrite","rootmost","rootMostPath","subtree","newWriteTree","compoundWriteAddWrites","newWrite","compoundWriteRemoveWrite","compoundWriteHasCompleteWrite","compoundWriteGetCompleteNode","compoundWriteGetCompleteChildren","compoundWriteChildCompoundWrite","shadowingNode","compoundWriteIsEmpty","compoundWriteApply","applySubtreeWrite","writeTree","priorityWrite","writeTreeChildWrites","newWriteTreeRef","writeTreeAddOverwrite","writeId","writeTreeGetWrite","record","writeTreeRemoveWrite","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","writeTreeRecordContainsPath_","writeTreeResetTree_","writeRecord","writeTreeLayerTree_","writeTreeDefaultFilter_","writes","treeRoot","writePath","deepNode","writeTreeCalcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","subMerge","layeredCache","merge","mergeAtPath","writeTreeCalcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","writeTreeCalcEventCacheAfterServerOverwrite","existingEventSnap","existingServerSnap","childMerge","writeTreeCalcCompleteChild","writeTreeShadowingWrite","writeTreeCalcIndexedSlice","completeServerData","reverse","toIterate","nodes","writeTreeRefCalcCompleteEventCache","writeTreeRef","writeTreeRefCalcCompleteEventChildren","writeTreeRefCalcEventCacheAfterServerOverwrite","writeTreeRefShadowingWrite","writeTreeRefCalcIndexedSlice","writeTreeRefCalcCompleteChild","existingServerCache","writeTreeRefChild","ChildChangeAccumulator","oldChange","oldType","NoCompleteChildSource_","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","viewProcessorAssertIndexed","viewProcessor","viewProcessorApplyOperation","oldViewCache","operation","writesCache","completeCache","accumulator","filterServerNode","overwrite","viewProcessorApplyUserOverwrite","viewProcessorApplyServerOverwrite","viewProcessorApplyUserMerge","viewProcessorApplyServerMerge","ackUserWrite","viewProcessorRevertUserWrite","viewProcessorAckUserWrite","viewProcessorListenComplete","viewProcessorMaybeAddValueEvent","isLeafOrEmpty","oldCompleteSnap","viewProcessorGenerateEventCacheAfterServerEvent","changePath","oldEventSnap","newEventCache","completeEventChildren","completeNode","oldEventNode","updatedPriority","childChangePath","newEventChild","eventChildUpdate","changedSnap","oldServerSnap","newServerCache","serverFilter","newServerNode","oldChild","newEventSnap","viewProcessorCacheHasChild","changedChildren","curViewCache","viewProcessorApplyMerge","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","mergePath","serverCachePath","oldServerNode","oldEventCache","serverChildren","viewGetCompleteServerCache","view","cache","viewApplyOperation","viewGenerateEventsForChanges_","eventRegistration","referenceConstructor$1","syncPointSetReferenceConstructor","syncPointApplyOperation","syncPoint","optCompleteServerCache","syncPointGetCompleteServerCache","referenceConstructor","syncTreeSetReferenceConstructor","SyncTree","listenProvider_","syncTreeApplyUserOverwrite","syncTree","syncTreeApplyOperationToSyncPoints_","syncTreeAckUserWrite","syncTreeApplyServerOverwrite","syncTreeApplyServerMerge","changeTree","syncTreeApplyTaggedQueryOverwrite","queryKey","syncTreeQueryKeyForTag_","syncTreeParseQueryKey_","queryPath","syncTreeApplyTaggedOperation_","syncTreeApplyTaggedQueryMerge","syncTreeCalcCompleteEventCache","syncTreeApplyOperationHelper_","syncPointTree","syncTreeApplyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","splitIndex","ExistingValueProvider","DeferredValueProvider","generateWithValues","values","resolveDeferredLeafValue","existingVal","serverValues","resolveScalarDeferredValue","resolveComplexDeferredValue","existing","unused","existingNode","resolveDeferredValueTree","resolveDeferredValue","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","Tree","parent","treeSubTree","pathObj","treeGetValue","treeSetValue","treeUpdateParents","treeHasChildren","treeIsEmpty","treeForEachChild","treeForEachDescendant","includeSelf","childrenFirst","treeForEachAncestor","treeGetPath","treeUpdateChild","childEmpty","childExists","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidPathString","isValidRootPathString","validateFirebaseData","path_","hasDotValue","hasActualChild","validateUrl","parsedUrl","EventQueue","eventQueueQueueEvents","eventQueue","eventDataList","currList","eventQueueRaiseEventsForChangedPath","changedPath","eventQueueRaiseQueuedEventsMatchingPredicate","eventPath","sentAll","eventList","eventListRaise","eventFn","INTERRUPT_REASON","MAX_TRANSACTION_RETRIES","Repo","forceRestClient_","appCheckProvider_","repoStart","repo","appId","authOverride","isMerge","repoOnDataUpdate","repoOnConnectStatus","connectStatus","repoOnServerInfoUpdate","infoEvents","repoUpdateInfo","repoServerTime","repoGenerateServerValues","taggedChildren","raw","taggedSnap","affectedPath","repoRerunTransactions","repoRunOnDisconnectEvents","repoGetNextWriteId","repoLog","resolvedOnDisconnectTree","resolved","repoAbortTransactions","repoInterrupt","repoGetLatestState","excludeSets","repoSendReadyTransactions","repoPruneCompletedTransactionsBelowNode","queue","repoBuildTransactionQueue","transaction","repoSendTransactionQueue","setsToIgnore","txn","latestState","snapToSend","latestHash","dataToSend","pathToSend","rootMostTransactionNode","repoGetAncestorTransactionNode","repoRerunTransactionQueue","abortTransaction","abortReason","currentNode","newDataNode","oldWriteId","newNodeResolved","unwatcher","transactionNode","transactionQueue","repoAggregateTransactionQueuesForNode","nodeQueue","to","from","repoAbortTransactionsOnNode","lastSent","decodePath","pathStringDecoded","piece","decodeQuery","queryString","segment","kv","parseRepoInfo","dataURL","parseDatabaseURL","subdomain","scheme","colonInd","slashInd","questionMarkInd","hostWithoutPort","dotInd","QueryImpl","_repo","_path","_queryParams","_orderByCalled","ReferenceImpl","sameRepo","samePath","sameQueryIdentifier","parentPath","ref","FIREBASE_DATABASE_EMULATOR_HOST_VAR","repos","useRestClient","repoManagerApplyEmulatorSettings","tokenProvider","repoManagerDatabaseFromApp","authProvider","dbUrl","dbEmulatorHost","authTokenProvider","repoManagerCreateRepo","Database","repoManagerDeleteRepo","appRepos","_repoInternal","apiName","getDatabase","emulator","connectDatabaseEmulator","registerDatabase","SDK_VERSION$1","onEcho"],"mappings":"UAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAmBA,MAAMA,GAAY,CAId,YAAa,GAIb,WAAY,GAIZ,YAAa,mBACjB,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAmBA,MAAMC,EAAS,SAAUC,EAAWC,EAAS,CACzC,GAAI,CAACD,EACD,MAAME,GAAeD,CAAO,CAEpC,EAIMC,GAAiB,SAAUD,EAAS,CACtC,OAAO,IAAI,MAAM,sBACbH,GAAU,YACV,6BACAG,CAAO,CACf,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAgBA,MAAME,GAAsB,SAAUC,EAAK,CAEvC,MAAMC,EAAM,CAAA,EACZ,IAAIC,EAAI,EACR,QAAS,EAAI,EAAG,EAAIF,EAAI,OAAQ,IAAK,CAC7B,IAAAG,EAAIH,EAAI,WAAW,CAAC,EACpBG,EAAI,IACJF,EAAIC,GAAG,EAAIC,EAENA,EAAI,MACLF,EAAAC,GAAG,EAAKC,GAAK,EAAK,IAClBF,EAAAC,GAAG,EAAKC,EAAI,GAAM,MAEhBA,EAAI,SAAY,OACtB,EAAI,EAAIH,EAAI,SACX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