Kargi-Sitesi/node_modules/firebase/firebase-firestore-lite.js.map

1 line
No EOL
808 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{"version":3,"file":"firebase-firestore-lite.js","sources":["../util/src/crypt.ts","../util/src/defaults.ts","../util/src/global.ts","../util/src/errors.ts","../util/src/obj.ts","../util/src/compat.ts","../component/src/component.ts","../logger/src/logger.ts","../firestore/src/auth/user.ts","../firestore/src/core/version.ts","../firestore/src/util/log.ts","../firestore/src/platform/browser/format_json.ts","../firestore/src/util/assert.ts","../firestore/src/util/error.ts","../firestore/src/util/promise.ts","../firestore/src/api/credentials.ts","../firestore/src/core/database_info.ts","../firestore/src/model/path.ts","../firestore/src/model/document_key.ts","../firestore/src/util/input_validation.ts","../firestore/src/api/long_polling_options.ts","../firestore/src/util/debug_uid.ts","../firestore/src/util/types.ts","../firestore/src/remote/rest_connection.ts","../firestore/src/remote/rpc_error.ts","../firestore/src/platform/browser_lite/fetch_connection.ts","../firestore/src/core/aggregate.ts","../firestore/src/platform/browser/random_bytes.ts","../firestore/src/util/misc.ts","../firestore/src/util/obj.ts","../firestore/src/util/base64_decode_error.ts","../firestore/src/util/byte_string.ts","../firestore/src/platform/browser/base64.ts","../firestore/src/model/normalize.ts","../firestore/src/lite-api/timestamp.ts","../firestore/src/model/server_timestamps.ts","../firestore/src/model/values.ts","../firestore/src/core/bound.ts","../firestore/src/core/filter.ts","../firestore/src/core/order_by.ts","../firestore/src/core/snapshot_version.ts","../firestore/src/util/sorted_map.ts","../firestore/src/util/sorted_set.ts","../firestore/src/model/field_mask.ts","../firestore/src/model/object_value.ts","../firestore/src/model/document.ts","../firestore/src/core/target.ts","../firestore/src/core/query.ts","../firestore/src/remote/number_serializer.ts","../firestore/src/model/transform_operation.ts","../firestore/src/model/mutation.ts","../firestore/src/remote/serializer.ts","../firestore/src/platform/browser/serializer.ts","../firestore/src/remote/backoff.ts","../firestore/src/remote/datastore.ts","../firestore/src/lite-api/components.ts","../firestore/src/platform/browser_lite/connection.ts","../firestore/src/lite-api/settings.ts","../firestore/src/local/lru_garbage_collector.ts","../firestore/src/local/lru_garbage_collector_impl.ts","../firestore/src/lite-api/database.ts","../util/src/emulator.ts","../firestore/src/lite-api/aggregate_types.ts","../firestore/src/lite-api/reference.ts","../firestore/src/lite-api/bytes.ts","../firestore/src/lite-api/field_path.ts","../firestore/src/lite-api/field_value.ts","../firestore/src/lite-api/geo_point.ts","../firestore/src/lite-api/vector_value.ts","../firestore/src/util/array.ts","../firestore/src/lite-api/user_data_reader.ts","../firestore/src/lite-api/snapshot.ts","../firestore/src/lite-api/query.ts","../firestore/src/lite-api/reference_impl.ts","../firestore/src/lite-api/user_data_writer.ts","../firestore/src/lite-api/aggregate.ts","../firestore/src/lite-api/field_value_impl.ts","../firestore/src/lite-api/write_batch.ts","../firestore/src/core/transaction.ts","../firestore/src/core/transaction_options.ts","../firestore/src/core/transaction_runner.ts","../firestore/src/platform/browser/dom.ts","../firestore/src/util/async_queue.ts","../firestore/src/util/async_queue_impl.ts","../firestore/src/local/simple_db.ts","../firestore/src/lite-api/transaction.ts","../firestore/lite/register.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 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\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record<string, string>;\n emulatorHosts?: Record<string, string>;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record<string, string> | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = <T extends ExperimentalKey>(\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function contains<T extends object>(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet<T extends object, K extends keyof T>(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map<K extends string, V, U>(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record<string, unknown>)[k];\n const bProp = (b as Record<string, unknown>)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n service: Compat<ExpService> | ExpService\n): ExpService {\n if (service && (service as Compat<ExpService>)._delegate) {\n return (service as Compat<ExpService>)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\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 semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n * <ul>\n * <li>`debug` for the most verbose logging level, primarily for\n * debugging.</li>\n * <li>`error` to log errors only.</li>\n * <li><code>`silent` to turn off logging.</li>\n * </ul>\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\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/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\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 */\nexport function fail(failure: string = 'Unexpected state'): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message =\n `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;\n logError(message);\n\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 new Error(message);\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 */\nexport function hardAssert(\n assertion: boolean,\n message?: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\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 */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast<T>(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as 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 */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\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' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\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' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\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 * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver<R> {\n (value: R | Promise<R>): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred<R = void> {\n promise: Promise<R>;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver<R>;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver<R>, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence<T>(\n values: T[],\n fn: (value: T) => Promise<void>\n): Promise<void> {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider<User>;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map<string, string>;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener<T> = (credential: T) => Promise<void>;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider<T> {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<T>\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise<Token | null>;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider<User> {\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n constructor(private token: Token) {}\n\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 private changeListener: CredentialChangeListener<User> | null = null;\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider<User> {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider<FirebaseAuthInternalName>) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise<Token | null> {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: (() => void) | undefined;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider<FirebaseAuthInternalName>) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 'Token listener already added'\n );\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise<void> = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\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 nextToken = new Deferred<void>();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred<void>();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n if (this.tokenListener) {\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n }\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\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 auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred<void>();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise<Token | null> {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\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 initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\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 if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth && this.tokenListener) {\n this.auth.removeAuthTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\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 private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\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 */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map<string, string> {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\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 */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider<string>\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener: AppCheckTokenListener | undefined;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n\n constructor(\n private appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 'Token listener already added'\n );\n\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise<void> = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n if (this.tokenListener) {\n this.appCheck.addTokenListener(this.tokenListener);\n }\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\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 appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise<Token | null> {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck && this.tokenListener) {\n this.appCheck.removeTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider<string> {\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider<string> {\n private appCheck: FirebaseAppCheckInternal | null = null;\n\n constructor(\n private appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise<Token | null> {\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider<User> {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class 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(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath<B extends BasePath<B>> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n static comparator<T extends BasePath<T>>(\n p1: BasePath<T>,\n p2: BasePath<T>\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const left = p1.get(i);\n const right = p2.get(i);\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n }\n if (p1.length < p2.length) {\n return -1;\n }\n if (p1.length > p2.length) {\n return 1;\n }\n return 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath<ResourcePath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\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\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\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 */\n static fromString(...pathComponents: string[]): ResourcePath {\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\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and trailing slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath<FieldPath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\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 */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\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 */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.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\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\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 */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\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 */\nexport function cast<T>(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${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/**\n * Options that configure the SDKs underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\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/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = 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 */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\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 */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\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/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\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 value === 0 && 1 / value === 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 */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\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.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\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 false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC<Req, Resp>(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise<Resp> {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n return this.performRPCRequest<Req, Resp>(rpcName, url, headers, req).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise<Resp[]> {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC<Req, Resp[]>(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream<Req, Resp>(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<Req, Resp>;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\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 headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest<Req, Resp>(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise<Resp>;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\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 */\n terminate(): void {\n // No-op\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\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 */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\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 */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.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 Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.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 Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\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 */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\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 */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\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 */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\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 logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\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 */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream<Req, Resp>(\n rpcName: string,\n token: Token | null\n ): Stream<Req, Resp> {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest<Req, Resp>(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise<Resp> {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n response = await fetch(url, {\n method: 'POST',\n headers,\n body: requestJson\n });\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\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\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler<E> = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\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 */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.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 if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator<T>(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable<T> {\n isEqual(other: T): boolean;\n}\n\nexport interface Iterable<V> {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals<T>(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict<V> {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach<V>(\n obj: Dict<V> | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray<V, R>(\n obj: Dict<V>,\n fn: (element: V, key: string, obj: Dict<V>) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty<V>(obj: Dict<V>): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\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/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\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 */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator<number> {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\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 if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 'Cannot normalize null or undefined timestamp.');\n\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 (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 'invalid timestamp: ' + date);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, 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 */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\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 */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\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 */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\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 */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\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 readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\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 */\n toDate(): Date {\n return new Date(this.toMillis());\n }\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 */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\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 */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n /** Returns a JSON-serializable representation of this `Timestamp`. */\n toJSON(): { seconds: number; nanoseconds: number } {\n return { seconds: this.seconds, 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 */\n valueOf(): string {\n // This method returns a string of the form <seconds>.<nanoseconds> where\n // <seconds> is translated to have a non-negative value and both <seconds>\n // and <nanoseconds> 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 <seconds> 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 adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\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 */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\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 if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\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 */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value as ProtoValue,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { arrayEquals, primitiveComparator } from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nexport const TYPE_KEY = '__type__';\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const VECTOR_VALUE_SENTINEL = '__vector__';\nexport const VECTOR_MAP_VECTORS_KEY = 'value';\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n } else if (isVectorValue(value)) {\n return TypeOrder.VectorValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail('Unexpected value type: ' + JSON.stringify(left));\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return primitiveComparator(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.VectorValue:\n return compareVectors(left.mapValue!, right.mapValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail('Invalid value type: ' + leftType);\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareVectors(left: MapValue, right: MapValue): number {\n const leftMap = left.fields || {};\n const rightMap = right.fields || {};\n\n // The vector is a map, but only vector value is compared.\n const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n\n const lengthCompare = primitiveComparator(\n leftArrayValue?.values?.length || 0,\n rightArrayValue?.values?.length || 0\n );\n if (lengthCompare !== 0) {\n return lengthCompare;\n }\n\n return compareArrays(leftArrayValue!, rightArrayValue!);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\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 leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\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 sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\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 */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case 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 value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Returns true if `value` is a VetorValue. */\nexport function isVectorValue(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === VECTOR_VALUE_SENTINEL;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\nexport const MIN_VECTOR_VALUE = {\n mapValue: {\n fields: {\n [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {}\n }\n }\n }\n};\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return MIN_VECTOR_VALUE;\n }\n return { mapValue: {} };\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return MIN_VECTOR_VALUE;\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return { mapValue: {} };\n }\n return MAX_VALUE;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\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\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\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 */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown FieldFilter operator: ' + this.op);\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter 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 (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\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 filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail('Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return other !== null && !arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\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\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\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 */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator<K> = (key1: K, key2: K) => number;\n\nexport interface Entry<K, V> {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap<K, V> {\n // visible for testing\n root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n\n constructor(\n public comparator: Comparator<K>,\n root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\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<T>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\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<T>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator<K, V> {\n private isReverse: boolean;\n private nodeStack: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>>;\n\n constructor(\n node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n startKey: K | null,\n comparator: Comparator<K>,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\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(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry<K, V> {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry<K, V> | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode<K, V> {\n readonly color: boolean;\n readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode<any, any> = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBNode<K, V> {\n return new LLRBNode<K, V>(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\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<T>(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode<K, V>).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode<K, V>).inorderTraversal(action)\n );\n }\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<T>(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode<K, V>).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode<K, V>).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode<K, V> {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode<K, V>).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode<K, V> = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator<K>\n ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n let smallest: LLRBNode<K, V>;\n let n: LLRBNode<K, V> = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode<K, V>).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode<K, V>).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode<K, V> {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode<K, V>).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode<K, V> {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode<K, V> {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode<K, V>).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode<K, V> {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode<K, V>).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode<K, V> {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\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 protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = (this.left as LLRBNode<K, V>).check();\n if (blackDepth !== (this.right as LLRBNode<K, V>).check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode<K, V> {\n get key(): never {\n throw fail('LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail('LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail('LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail('LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail('LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBEmptyNode<K, V> {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n return new LLRBNode<K, V>(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode<unknown, unknown>();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\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 */\nexport class SortedSet<T> {\n private data: SortedMap<T, boolean>;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap<T, boolean>(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start &lt;= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator<T, boolean>;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet<T> {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet<T> {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet<T>): SortedSet<T> {\n let result: SortedSet<T> = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet<T>): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap<T, boolean>): SortedSet<T> {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator<T> {\n constructor(private iter: SortedMapIterator<T, boolean>) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\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 */\nexport function diffSortedSets<T>(\n before: SortedSet<T>,\n after: SortedSet<T>,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator<T>(it: SortedSetIterator<T>): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\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 */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\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 */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\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 */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject<T> {\n [name: string]: T;\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 */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ 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 */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\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 */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\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 */\n setAll(data: Map<FieldPath, ProtoValue | null>): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\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 */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\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 */\n private getFieldsMap(path: FieldPath): Record<string, ProtoValue> {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record<string, ProtoValue>,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be synced or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\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 */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\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 */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\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 if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\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 */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\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 */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\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\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = 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 */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\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 */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\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 */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map</* fieldPath = */ string, ProtoValue>();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case 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 values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case 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 values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\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 */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\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 */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\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 targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\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 (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\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 */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\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 (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet<FieldPath>(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\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 if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\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 */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\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 memoizedAggregateTarget: Target | null = null;\n\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(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\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 */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet<FieldPath> {\n let result = new SortedSet<FieldPath>(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\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 */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set<string>();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\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<FieldPath>` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet<FieldPath> =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\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 */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\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.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\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 orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\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 */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\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 */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + orderBy.dir);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\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 */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\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\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\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 */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\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 if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\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 */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\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 */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\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 baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.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\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class 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 readonly version: SnapshotVersion,\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 readonly transformResults: Array<ProtoValue | null>\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\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 */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\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 */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\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 */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\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 if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\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 */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\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 */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\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 */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\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 newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\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 */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\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 document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map<FieldPath, ProtoValue | null> {\n const result = new Map<FieldPath, ProtoValue | null>();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\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 */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array<ProtoValue | null>\n): Map<FieldPath, ProtoValue> {\n const transformResults = new Map<FieldPath, ProtoValue>();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\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 */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map<FieldPath, ProtoValue> {\n const transformResults = new Map<FieldPath, ProtoValue>();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\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 document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\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 */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\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 */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\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: <number> } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\nfunction fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined ||\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 value instanceof Buffer ||\n value instanceof Uint8Array,\n 'value must be undefined, Buffer, or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\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 if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 'tried to deserialize invalid key ' + resourceName.toString()\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\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 change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.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 version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[],\n skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record<string, string>;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record<string, string> = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\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 serverAlias = skipAliasing\n ? aggregate.alias\n : `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap<string> | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.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 result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified operator');\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail('Unrecognized filter type ' + JSON.stringify(filter));\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\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/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\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 */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation<void> | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\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 private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\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 */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\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 */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\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 */\n backoffAndRun(op: () => Promise<void>): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\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 */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider<User>,\n readonly appCheckCredentials: CredentialsProvider<string>,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC<Req, Resp>(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise<Resp> {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC<Req, Resp>(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise<Resp[]> {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC<Req, Resp>(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise<void> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise<Document[]> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map<string, Document>();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise<Document[]> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\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 unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap<Value>\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider<User>;\n _appCheckCredentials: CredentialsProvider<string>;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map<FirestoreService, Datastore>();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n\n localCache?: FirestoreLocalCache;\n}\n\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 */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\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 =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\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\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap<TargetId, unknown>;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\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 readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\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 readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults>;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise<number>;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<number>;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise<void>;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number>;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void>;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\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 */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet<BufferEntry> = new SortedSet<BufferEntry>(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\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 */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation<void> | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise<number> {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<ListenSequenceNumber> {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve<LruResults>({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n\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 private _terminateTask: Promise<void> | 'notTerminated' = 'notTerminated';\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider<User>,\n public _appCheckCredentials: CredentialsProvider<string>,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== 'notTerminated';\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise<void> {\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 if (this._terminateTask === 'notTerminated') {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n async _restart(): Promise<void> {\n // The `_terminateTask` must equal 'notTerminated' after restart to\n // signal that client is in a state that accepts API calls.\n if (this._terminateTask === 'notTerminated') {\n await this._terminate();\n } else {\n this._terminateTask = 'notTerminated';\n }\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\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 */\n protected _terminate(): Promise<void> {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, 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 `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, 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 `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\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 */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const settings = firestore._getSettings();\n const newHostSetting = `${host}:${port}`;\n\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n\n firestore._setSettings({\n ...settings,\n host: newHostSetting,\n ssl: false\n });\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\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 of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial<FirebaseIdToken>;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\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\nimport { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField<T> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField<T>\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(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType<typeof sum>\n | ReturnType<typeof average>\n | ReturnType<typeof count>;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData<T extends AggregateSpec> = {\n [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query<AppModelType, DbModelType>;\n\n /** @hideconstructor */\n constructor(\n query: Query<AppModelType, DbModelType>,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap<Value>\n ) {\n this.query = query;\n }\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 */\n data(): AggregateSpecData<AggregateSpecType> {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData<AggregateSpecType>;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to TypeScript's `Partial<T>`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue<T> =\n | Partial<T>\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue<T> =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue<T[K]> | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData<T> = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData<T[K]> | FieldValue } & NestedUpdateFields<T>\n : Partial<T>;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array<string | FieldPath>;\n };\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 */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query<DocumentData, DocumentData>` that does not use a\n * converter.\n */\n withConverter(converter: null): Query<DocumentData, DocumentData>;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): Query<NewAppModelType, NewDbModelType>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): Query<NewAppModelType, NewDbModelType> {\n return new Query<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._query\n );\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 */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference<AppModelType, DbModelType> {\n return new CollectionReference<AppModelType, DbModelType>(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): DocumentReference<NewAppModelType, NewDbModelType>;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference<DocumentData, DocumentData>` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference<DocumentData, DocumentData>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): DocumentReference<NewAppModelType, NewDbModelType> {\n return new DocumentReference<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._key\n );\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 */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query<AppModelType, DbModelType> {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter<AppModelType, DbModelType> | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\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 */\n get parent(): DocumentReference<DocumentData, DocumentData> | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): CollectionReference<NewAppModelType, NewDbModelType>;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference<DocumentData, DocumentData>` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference<DocumentData, DocumentData>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): CollectionReference<NewAppModelType, NewDbModelType> {\n return new CollectionReference<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n parent:\n | Firestore\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData> {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\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/**\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 */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query<DocumentData, DocumentData> {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-generated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n parent:\n | Firestore\n | CollectionReference<AppModelType, DbModelType>\n | DocumentReference<AppModelType, DbModelType>,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType> {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference<AppModelType, DbModelType>(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\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 */\nexport function refEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>,\n right:\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\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 */\nexport function queryEqual<AppModelType, DbModelType extends DocumentData>(\n left: Query<AppModelType, DbModelType>,\n right: Query<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\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 */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\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 */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\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 */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\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 */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\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 */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\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(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\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 */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._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 */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\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 */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\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(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\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 */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /** Returns a JSON-serializable representation of this GeoPoint. */\n toJSON(): { latitude: number; longitude: number } {\n return { latitude: this._lat, 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 */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._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\nimport { isPrimitiveArrayEqual } from '../util/array';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link FieldValue.vector}.\n *\n * @class VectorValue\n */\nexport class VectorValue {\n private readonly _values: number[];\n\n /**\n * @private\n * @internal\n */\n constructor(values: number[] | undefined) {\n // Making a copy of the parameter.\n this._values = (values || []).map(n => n);\n }\n\n /**\n * Returns a copy of the raw number array form of the vector.\n */\n toArray(): number[] {\n return this._values.map(n => n);\n }\n\n /**\n * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\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/**\n * Returns true iff the array contains the value using strong equality.\n */\nexport function includes<T>(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value matching the predicate\n */\nexport function some<T>(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex<A>(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\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 */\nexport function diffArrays<T>(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\n }\n}\n\n/**\n * Verifies equality for an array of objects using the `isEqual` interface.\n *\n * @private\n * @internal\n * @param left Array of objects supporting `isEqual`.\n * @param right Array of objects supporting `isEqual`.\n * @return True if arrays are equal.\n */\nexport function isArrayEqual<T extends { isEqual: (t: T) => boolean }>(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\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 */\nexport function isPrimitiveArrayEqual<T extends number | string>(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\n TYPE_KEY,\n VECTOR_MAP_VECTORS_KEY,\n VECTOR_VALUE_SENTINEL\n} from '../model/values';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toDouble, toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\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(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial<ContextSettings>): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof 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 */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict<unknown>, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat<PublicFieldPath>,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\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 i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.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 */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\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 */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input 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 parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.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 } else {\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 if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input 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 (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nfunction parseObject(\n obj: Dict<unknown>,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict<ProtoValue> = {};\n\n if (isEmpty(obj)) {\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 if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\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 */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value 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 timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else if (value instanceof VectorValue) {\n return parseVectorValue(value, context);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Creates a new VectorValue proto value (using the internal format).\n */\nexport function parseVectorValue(\n value: VectorValue,\n context: ParseContextImpl\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: VECTOR_VALUE_SENTINEL\n },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {\n values: value.toArray().map(value => {\n if (typeof value !== 'number') {\n throw context.createError(\n 'VectorValues must only contain numeric values.'\n );\n }\n\n return toDouble(context.serializer, value);\n })\n }\n }\n }\n };\n\n return { mapValue };\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 */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue) &&\n !(input instanceof VectorValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict<unknown> {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat<PublicFieldPath>,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = 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 */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue<number>) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise<void> {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter<Post, PostDbModel> {\n * toFirestore(post: WithFieldValue<Post>): WithFieldValue<PostDbModel> {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise<void> {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue<Post>` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue<Post>`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue<Post>\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot<Post> = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue<PostDbModel>` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue<PostDbModel>`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue<PostDbModel>\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot<Post> = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>\n ): AppModelType;\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(<field>)` 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 */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\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\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference<AppModelType, DbModelType> {\n return new DocumentReference<AppModelType, DbModelType>(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n return this._document !== null;\n }\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 */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else 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 snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\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(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\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(<field>)` 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 */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\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(): AppModelType {\n return super.data() as AppModelType;\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 */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query<AppModelType, DbModelType>;\n\n /** @hideconstructor */\n constructor(\n _query: Query<AppModelType, DbModelType>,\n readonly _docs: Array<QueryDocumentSnapshot<AppModelType, DbModelType>>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\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 */\n forEach(\n callback: (\n result: QueryDocumentSnapshot<AppModelType, DbModelType>\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\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 */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>,\n right:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat<FieldPath>\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._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 */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType>;\n}\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 */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query<AppModelType, DbModelType>;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n ...queryConstraints: QueryConstraint[]\n): Query<AppModelType, DbModelType>;\n\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query<AppModelType, DbModelType> {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\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 */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\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 \"&lt;\", \"&lt;=\", \"==\", \"&lt;\",\n * \"&lt;=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\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 */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\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 */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\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 */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\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 */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\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 */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\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 */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\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 */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, 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 */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, 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 */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query<AppModelType, DbModelType>(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\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 */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>,\n methodName: string,\n docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\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 */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\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 orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\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 */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\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 */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\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.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\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 */\nexport function applyFirestoreDataConverter<T>(\n converter: UntypedFirestoreDataConverter<T> | null,\n value: WithFieldValue<T> | PartialWithFieldValue<T>,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\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 convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue<T>);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(result.length === 1, 'Expected a single document result');\n const document = result[0];\n return new DocumentSnapshot<AppModelType, DbModelType>(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot<AppModelType, DbModelType>(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot<AppModelType, DbModelType>(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * 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 * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * 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 * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update 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 * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update 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 * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete 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 * @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.\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * 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 * @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 * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n reference = cast<CollectionReference<AppModelType, DbModelType>>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue<AppModelType>\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { VECTOR_MAP_VECTORS_KEY, typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n case TypeOrder.VectorValue:\n return this.convertVectorValue(value.mapValue!);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap<Value> | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n /**\n * @internal\n */\n convertVectorValue(mapValue: ProtoMapValue): VectorValue {\n const values = mapValue.fields?.[\n VECTOR_MAP_VECTORS_KEY\n ].arrayValue?.values?.map(value => {\n return normalizeNumber(value.doubleValue);\n });\n\n return new VectorValue(values);\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 'ReferenceValue is not valid ' + name\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\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\nimport { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\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 * @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 */\nexport function getCount<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField<number> },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField<number> } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\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 * @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 getAggregate(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 */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query<AppModelType, DbModelType>,\n aggregateResult: ApiClientObjectMap<Value>\n): AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType> {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\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 */\nexport function sum(field: string | FieldPath): AggregateField<number> {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\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 */\nexport function average(\n field: string | FieldPath\n): AggregateField<number | null> {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\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 */\nexport function count(): AggregateField<number> {\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 */\nexport function aggregateFieldEqual(\n left: AggregateField<unknown>,\n right: AggregateField<unknown>\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\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 */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>,\n right: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.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\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\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 */\nexport function deleteField(): FieldValue {\n return new 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 */\nexport function serverTimestamp(): FieldValue {\n return new 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 */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\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 ArrayUnionFieldValueImpl('arrayUnion', elements);\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 */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\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 ArrayRemoveFieldValueImpl('arrayRemove', elements);\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 */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\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 */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\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 */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise<void>\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): WriteBatch;\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType> | PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\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 */\n delete<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\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 */\n commit(): Promise<void> {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference<AppModelType, DbModelType>\n | Compat<DocumentReference<AppModelType, DbModelType>>,\n firestore: Firestore\n): DocumentReference<AppModelType, DbModelType> {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference<AppModelType, DbModelType>;\n }\n}\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 WriteBatch\n * is 500.\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 `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map</* path */ string, SnapshotVersion>();\n private mutations: Mutation[] = [];\n private committed = false;\n\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 private lastTransactionError: FirestoreError | null = null;\n\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 private writtenDocs: Set</* path= */ string> = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise<Document[]> {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise<void> {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail('Document in a transaction was a ' + doc.constructor.name);\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\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 */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.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(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\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\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\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\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\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\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner<T> {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise<T>,\n private readonly deferred: Deferred<T>\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise<T> | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error): boolean {\n if (error.name === 'FirebaseError') {\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 code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\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 Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\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 */\nexport class DelayedOperation<T extends unknown> implements PromiseLike<T> {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred<T>();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise<T>,\n private readonly removalCallback: (op: DelayedOperation<T>) => void\n ) {\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(err => {});\n }\n\n get promise(): Promise<T> {\n return this.deferred.promise;\n }\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 */\n static createAndSchedule<R extends unknown>(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<R>,\n removalCallback: (op: DelayedOperation<R>) => void\n ): DelayedOperation<R> {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\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 */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\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 */\n enqueueAndForget<T extends unknown>(op: () => Promise<T>): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n op: () => Promise<T>\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise<void>): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): DelayedOperation<T>;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\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 */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw 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\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise<unknown>;\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise<void>> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array<DelayedOperation<unknown>> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\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 private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor(tail: Promise<unknown> = Promise.resolve()) {\n this.tail = tail;\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\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 */\n enqueueAndForget<T extends unknown>(op: () => Promise<T>): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n op: () => Promise<T>\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue<T extends unknown>(op: () => Promise<T>): Promise<T> {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise<T>(() => {});\n }\n\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 task = new Deferred<T>();\n return this.enqueueInternal<unknown>(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise<void>): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise<void> {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.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.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal<T extends unknown>(op: () => Promise<T>): Promise<T> {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\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 error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): DelayedOperation<T> {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overridden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule<T>(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation<unknown>)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation<unknown>);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + getMessageOrStack(this.failure));\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise<void> {\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 currentTail: Promise<unknown>;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\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 */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise<void> {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().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.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation<unknown>): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\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 */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise<void>;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred<void>();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise<void> {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\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 maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore<KeyType, ValueType> 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 */\n store<KeyType extends IDBValidKey, ValueType extends unknown>(\n storeName: string\n ): SimpleDbStore<KeyType, ValueType> {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore<KeyType, ValueType>(store);\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 */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise<void> {\n logDebug(LOG_TAG, 'Removing database:', name);\n return wrapRequest<void>(window.indexedDB.deleteDatabase(name)).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\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\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\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\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for users running version < 4.5.\n const androidVersion = getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore<KeyType extends IDBValidKey, ValueType extends unknown>(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore<KeyType, ValueType> {\n return txn.store<KeyType, ValueType>(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\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(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\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 if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise<IDBDatabase> {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\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 request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction<T>(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise<T>\n ): Promise<T> {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject<T>(error);\n })\n .toPromise();\n\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 transactionFnResult.catch(() => {});\n\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 transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\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\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 const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\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 */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\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 */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise<void> {\n return wrapRequest<void>(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback<KeyType, ValueType> = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise<void>;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndexedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\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 */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise<void>;\n put(key: KeyType, value: ValueType): PersistencePromise<void>;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise<void> {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '<auto-key>', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest<void>(request);\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 */\n add(value: ValueType): PersistencePromise<KeyType> {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest<KeyType>(request);\n }\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 */\n get(key: KeyType): PersistencePromise<ValueType | null> {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest<any>(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise<void> {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest<void>(request);\n }\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 */\n count(): PersistencePromise<number> {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest<number>(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise<ValueType[]>;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise<ValueType[]>;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise<ValueType[]>;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise<ValueType[]>;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<ValueType[]> {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise<ValueType[]> {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise<void>;\n deleteAll(range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<void> {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n options: IterateOptions,\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback<KeyType, ValueType>,\n callback?: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback<KeyType, ValueType>;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\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 */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise<boolean>\n ): PersistencePromise<void> {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n const results: Array<PersistencePromise<void>> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise<void> = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\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 */\nfunction wrapRequest<R>(request: IDBRequest): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\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 */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\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 */\n get<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>\n ): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot<AppModelType, DbModelType>(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot<AppModelType, DbModelType>(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n `BatchGetDocumentsRequest returned unexpected document: ${doc}`\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): this;\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n value: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\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 */\n delete<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\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 */\nexport function runTransaction<T>(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise<T>,\n options?: TransactionOptions\n): Promise<T> {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred<T>();\n new TransactionRunner<T>(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n"],"names":["stringToByteArray","str","out","p","i","length","c","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","push","join","encodeString","btoa","decodeString","bytes","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","name","base64urlEncodeWithoutPadding","utf8Bytes","base64Encode","replace","getDefaultsFromGlobal","getGlobal","self","window","global","__FIREBASE_DEFAULTS__","getDefaultsFromCookie","document","match","cookie","e","decoded","console","error","base64Decode","JSON","parse","getDefaults","process","env","defaultsJsonString","getDefaultsFromEnvVariable","info","getDefaultEmulatorHostnameAndPort","productName","host","_a","_b","emulatorHosts","getDefaultEmulatorHost","separatorIndex","lastIndexOf","port","parseInt","substring","FirebaseError","code","message","customData","super","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replaceTemplate","PATTERN","_","key","value","fullMessage","deepEqual","a","b","aKeys","keys","bKeys","k","includes","aProp","bProp","isObject","thing","getModularInstance","_delegate","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","LogLevel","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","args","logLevel","now","Date","toISOString","method","User","uid","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","log","__PRIVATE_logDebug","msg","obj","map","__PRIVATE_argToString","__PRIVATE_logError","__PRIVATE_logWarn","__PRIVATE_formatJSON","stringify","fail","__PRIVATE_failure","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","toString","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_LiteAuthCredentialsProvider","__PRIVATE_authProvider","auth","onInit","then","__PRIVATE_tokenData","accessToken","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE__headers","__PRIVATE_getAuthToken","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","__PRIVATE_LiteAppCheckTokenProvider","__PRIVATE_appCheckProvider","appCheck","tokenResult","DatabaseInfo","databaseId","appId","persistenceKey","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","DatabaseId","projectId","database","static","isDefaultDatabase","other","BasePath","segments","offset","undefined","len","comparator","child","nameOrPath","slice","limit","forEach","segment","construct","popFirst","size","popLast","firstSegment","lastSegment","get","index","isEmpty","isPrefixOf","__PRIVATE_i","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","Math","min","left","right","ResourcePath","canonicalString","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","__PRIVATE_identifierRegExp","FieldPath","test","isValidIdentifier","isKeyField","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromString","emptyPath","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateDocumentPath","isDocumentKey","__PRIVATE_validateCollectionPath","__PRIVATE_valueDescription","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","description","__PRIVATE_validatePositiveNumber","n","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","__PRIVATE_FetchConnection","__PRIVATE_RestConnection","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_shouldResourcePathBeIncludedInRequest","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","appCheckToken","streamId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","random","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","__PRIVATE_performRPCRequest","response","err","__PRIVATE_invokeStreamingRPC","request","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","__PRIVATE_urlRpcName","terminate","__PRIVATE_openStream","async","body","__PRIVATE_requestJson","fetch","statusText","ok","__PRIVATE_errorResponse","json","__PRIVATE_errorMessage","__PRIVATE_AggregateImpl","alias","aggregateType","fieldPath","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","msCrypto","Uint8Array","getRandomValues","floor","__PRIVATE_AutoId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","__PRIVATE_primitiveComparator","__PRIVATE_arrayEquals","every","__PRIVATE_objectSize","count","hasOwnProperty","call","__PRIVATE_Base64DecodeError","ByteString","binaryString","__PRIVATE_decodeBase64","__PRIVATE_encoded","DOMException","array","__PRIVATE_binaryStringFromUint8Array","Symbol","iterator","done","toBase64","__PRIVATE_encodeBase64","raw","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","fromBase64String","fromUint8Array","Timestamp","nanoseconds","fromMillis","milliseconds","toDate","toMillis","_compareTo","toJSON","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","mapValue","fields","__type__","stringValue","__PRIVATE_getPreviousValue","previousValue","__previous_value__","__PRIVATE_getLocalWriteTime","localWriteTime","__local_write_time__","timestampValue","MAX_VALUE","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","v","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","comparison","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","_c","_d","__PRIVATE_compareMaps","__PRIVATE_leftKeys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","compare","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","assign","target","Bound","position","inclusive","__PRIVATE_boundEquals","Filter","FieldFilter","field","op","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","matchesComparison","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","result","__PRIVATE_subfilter","concat","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","fromName","__PRIVATE_extractDocumentKeysFromArrayValue","some","nullValue","OrderBy","dir","__PRIVATE_orderByEquals","SnapshotVersion","timestamp","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","range","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","add","delete","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","r","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","version","readTime","createTime","documentState","documentKey","empty","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_isCollectionGroupQuery","query","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","keyField","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","toNumber","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","TransformOperation","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","FieldTransform","transform","Precondition","updateTime","exists","isNone","Mutation","__PRIVATE_SetMutation","precondition","fieldTransforms","getFieldMask","__PRIVATE_PatchMutation","fieldMask","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","fromTimestamp","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_toName","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","__PRIVATE_toMutationDocument","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","from","allDescendants","__PRIVATE_toQueryPath","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","__PRIVATE_toInt32Proto","__PRIVATE_toStartAtCursor","cursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_toUnaryOrFieldFilter","unaryFilter","fieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_protos","__PRIVATE_toDocumentMask","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_queue","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","__PRIVATE_lastAttemptTime","reset","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","cancel","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","max","__PRIVATE_remainingDelayMs","enqueueAfterDelay","__PRIVATE_skipBackoff","skipDelay","__PRIVATE_DatastoreImpl","Datastore","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","__PRIVATE_invokeCommitRpc","datastore","mutations","__PRIVATE_datastoreImpl","writes","m","toMutation","mutation","update","updateMask","verify","updateTransforms","__PRIVATE_toFieldTransform","__PRIVATE_fieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_invokeBatchGetDocumentsRpc","documents","docs","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","newFoundDocument","__PRIVATE_fromMissing","missing","newNoDocument","__PRIVATE_datastoreInstances","__PRIVATE_getDatastore","firestore","_terminated","__PRIVATE_newConnection","__PRIVATE_makeDatabaseInfo","settings","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","_databaseId","app","_persistenceKey","_freezeSettings","__PRIVATE_newDatastore","_authCredentials","_appCheckCredentials","FirestoreSettingsImpl","credentials","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_app","_settings","_settingsFrozen","_terminateTask","_initialized","_setSettings","__PRIVATE_makeAuthCredentialsProvider","sessionIndex","iamToken","authTokenFactory","client","_getSettings","_delete","_terminate","__PRIVATE_removeComponents","initializeFirestore","provider","_getProvider","isInitialized","initialize","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","db","getImmediate","identifier","__PRIVATE_emulator","connectFirestoreEmulator","__PRIVATE_newHostSetting","mockUserToken","createMockUserToken","project","iat","sub","user_id","payload","iss","aud","exp","auth_time","firebase","sign_in_provider","identities","alg","_removeServiceInstance","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","Query","converter","_query","withConverter","DocumentReference","_key","_path","id","CollectionReference","__PRIVATE_newQueryForPath","parentPath","collection","pathSegments","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","newId","refEqual","queryEqual","__PRIVATE_queryEquals","__PRIVATE_targetEquals","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","documentId","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","configuration","__PRIVATE_childContextForField","__PRIVATE_childPath","context","__PRIVATE_arrayElement","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","reason","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","contains","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_fieldValue","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","element","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","fromDate","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_isPlainObject","getPrototypeOf","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","ref","snapshot","QueryDocumentSnapshot","fromFirestore","convertValue","QuerySnapshot","_docs","thisArg","snapshotEqual","arg","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_reader","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_create","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","__PRIVATE_subFilter","_getQueryConstraints","or","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","__PRIVATE_queryWithLimit","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","bound","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","operator","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","getDoc","reference","userDataWriter","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","__PRIVATE_invokeRunQueryRpc","q","__PRIVATE_fromDocument","reverse","setDoc","__PRIVATE_parsed","none","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","getCount","getAggregate","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_mapToArray","__PRIVATE_aggregate","__PRIVATE_invokeRunAggregationQueryRpc","__PRIVATE_aggregates","Z","__PRIVATE_aliasMap","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_skipAliasing","aggregations","__PRIVATE_aggregationNum","__PRIVATE_serverAlias","avg","sum","structuredAggregationQuery","__PRIVATE_queryToAggregateTarget","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","deleteField","serverTimestamp","arrayRemove","vector","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","commit","writeBatch","Transaction","readVersions","committed","lastTransactionError","writtenDocs","ensureCommitNotCalled","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","fromPath","__PRIVATE_docVersion","__PRIVATE_existingVersion","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","maxAttempts","__PRIVATE_TransactionRunner","updateFunction","deferred","__PRIVATE_attemptsRemaining","__PRIVATE_backoff","__PRIVATE_run","__PRIVATE_runWithBackOff","transaction","__PRIVATE_userPromise","__PRIVATE_tryRunUpdateFunction","enqueueAndForget","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","__PRIVATE_isPermanentError","getDocument","DelayedOperation","targetTimeMs","removalCallback","bind","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","setTimeout","handleDelayElapsed","clearTimeout","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","visibilityState","addEventListener","isShuttingDown","enqueue","enqueueAndForgetEvenWhileRestricted","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","enterRestrictedMode","purgeExistingTasks","removeEventListener","task","__PRIVATE_retryNextOp","shift","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","stack","createAndSchedule","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","verifyOperationInProgress","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","__PRIVATE_drain","__PRIVATE_skipDelaysForTimerId","splice","_transaction","lookup","runTransaction","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_newAsyncQueue","__PRIVATE_internalTransaction","__PRIVATE_registerFirestore","__PRIVATE_setSDKVersion","_registerComponent","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","apply","registerVersion"],"mappings":"8IAiBA,MAAMA,oBAAoB,SAAUC,GAElC,MAAMC,EAAgB,GACtB,IAAIC,EAAI,EACR,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAAII,OAAQD,IAAK,CACnC,IAAIE,EAAIL,EAAIM,WAAWH,GACnBE,EAAI,IACNJ,EAAIC,KAAOG,EACFA,EAAI,MACbJ,EAAIC,KAAQG,GAAK,EAAK,IAC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