From 42d5bdb7ec303f79febeb95023adced7592c4ed5 Mon Sep 17 00:00:00 2001
From: X-20A <155217226+X-20A@users.noreply.github.com>
Date: Fri, 22 Mar 2024 01:39:05 +0900
Subject: [PATCH] =?UTF-8?q?=E3=83=86=E3=82=B9=E3=83=88?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
compass/dist/main.js | 112 ++++++++++++++++++++++++++++++++++++++++-
compass/src/js/main.js | 23 +++++++++
2 files changed, 134 insertions(+), 1 deletion(-)
diff --git a/compass/dist/main.js b/compass/dist/main.js
index 9fe6383..b3b5efb 100644
--- a/compass/dist/main.js
+++ b/compass/dist/main.js
@@ -9,6 +9,28 @@
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
+/***/ "./node_modules/@firebase/firestore/dist/index.esm2017.js":
+/*!****************************************************************!*\
+ !*** ./node_modules/@firebase/firestore/dist/index.esm2017.js ***!
+ \****************************************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbstractUserDataWriter: () => (/* binding */ AbstractUserDataWriter),\n/* harmony export */ AggregateField: () => (/* binding */ AggregateField),\n/* harmony export */ AggregateQuerySnapshot: () => (/* binding */ AggregateQuerySnapshot),\n/* harmony export */ Bytes: () => (/* binding */ Bytes),\n/* harmony export */ CACHE_SIZE_UNLIMITED: () => (/* binding */ pe),\n/* harmony export */ CollectionReference: () => (/* binding */ CollectionReference),\n/* harmony export */ DocumentReference: () => (/* binding */ DocumentReference),\n/* harmony export */ DocumentSnapshot: () => (/* binding */ DocumentSnapshot),\n/* harmony export */ FieldPath: () => (/* binding */ FieldPath),\n/* harmony export */ FieldValue: () => (/* binding */ FieldValue),\n/* harmony export */ Firestore: () => (/* binding */ Firestore),\n/* harmony export */ FirestoreError: () => (/* binding */ FirestoreError),\n/* harmony export */ GeoPoint: () => (/* binding */ GeoPoint),\n/* harmony export */ LoadBundleTask: () => (/* binding */ LoadBundleTask),\n/* harmony export */ PersistentCacheIndexManager: () => (/* binding */ PersistentCacheIndexManager),\n/* harmony export */ Query: () => (/* binding */ Query),\n/* harmony export */ QueryCompositeFilterConstraint: () => (/* binding */ QueryCompositeFilterConstraint),\n/* harmony export */ QueryConstraint: () => (/* binding */ QueryConstraint),\n/* harmony export */ QueryDocumentSnapshot: () => (/* binding */ QueryDocumentSnapshot),\n/* harmony export */ QueryEndAtConstraint: () => (/* binding */ QueryEndAtConstraint),\n/* harmony export */ QueryFieldFilterConstraint: () => (/* binding */ QueryFieldFilterConstraint),\n/* harmony export */ QueryLimitConstraint: () => (/* binding */ QueryLimitConstraint),\n/* harmony export */ QueryOrderByConstraint: () => (/* binding */ QueryOrderByConstraint),\n/* harmony export */ QuerySnapshot: () => (/* binding */ QuerySnapshot),\n/* harmony export */ QueryStartAtConstraint: () => (/* binding */ QueryStartAtConstraint),\n/* harmony export */ SnapshotMetadata: () => (/* binding */ SnapshotMetadata),\n/* harmony export */ Timestamp: () => (/* binding */ Timestamp),\n/* harmony export */ Transaction: () => (/* binding */ Transaction),\n/* harmony export */ WriteBatch: () => (/* binding */ WriteBatch),\n/* harmony export */ _AutoId: () => (/* binding */ __PRIVATE_AutoId),\n/* harmony export */ _ByteString: () => (/* binding */ ByteString),\n/* harmony export */ _DatabaseId: () => (/* binding */ DatabaseId),\n/* harmony export */ _DocumentKey: () => (/* binding */ DocumentKey),\n/* harmony export */ _EmptyAppCheckTokenProvider: () => (/* binding */ __PRIVATE_EmptyAppCheckTokenProvider),\n/* harmony export */ _EmptyAuthCredentialsProvider: () => (/* binding */ __PRIVATE_EmptyAuthCredentialsProvider),\n/* harmony export */ _FieldPath: () => (/* binding */ FieldPath$1),\n/* harmony export */ _TestingHooks: () => (/* binding */ TestingHooks),\n/* harmony export */ _cast: () => (/* binding */ __PRIVATE_cast),\n/* harmony export */ _debugAssert: () => (/* binding */ __PRIVATE_debugAssert),\n/* harmony export */ _isBase64Available: () => (/* binding */ __PRIVATE_isBase64Available),\n/* harmony export */ _logWarn: () => (/* binding */ __PRIVATE_logWarn),\n/* harmony export */ _validateIsNotUsedTogether: () => (/* binding */ __PRIVATE_validateIsNotUsedTogether),\n/* harmony export */ addDoc: () => (/* binding */ addDoc),\n/* harmony export */ aggregateFieldEqual: () => (/* binding */ aggregateFieldEqual),\n/* harmony export */ aggregateQuerySnapshotEqual: () => (/* binding */ aggregateQuerySnapshotEqual),\n/* harmony export */ and: () => (/* binding */ and),\n/* harmony export */ arrayRemove: () => (/* binding */ arrayRemove),\n/* harmony export */ arrayUnion: () => (/* binding */ arrayUnion),\n/* harmony export */ average: () => (/* binding */ average),\n/* harmony export */ clearIndexedDbPersistence: () => (/* binding */ clearIndexedDbPersistence),\n/* harmony export */ collection: () => (/* binding */ collection),\n/* harmony export */ collectionGroup: () => (/* binding */ collectionGroup),\n/* harmony export */ connectFirestoreEmulator: () => (/* binding */ connectFirestoreEmulator),\n/* harmony export */ count: () => (/* binding */ count),\n/* harmony export */ deleteAllPersistentCacheIndexes: () => (/* binding */ deleteAllPersistentCacheIndexes),\n/* harmony export */ deleteDoc: () => (/* binding */ deleteDoc),\n/* harmony export */ deleteField: () => (/* binding */ deleteField),\n/* harmony export */ disableNetwork: () => (/* binding */ disableNetwork),\n/* harmony export */ disablePersistentCacheIndexAutoCreation: () => (/* binding */ disablePersistentCacheIndexAutoCreation),\n/* harmony export */ doc: () => (/* binding */ doc),\n/* harmony export */ documentId: () => (/* binding */ documentId),\n/* harmony export */ enableIndexedDbPersistence: () => (/* binding */ enableIndexedDbPersistence),\n/* harmony export */ enableMultiTabIndexedDbPersistence: () => (/* binding */ enableMultiTabIndexedDbPersistence),\n/* harmony export */ enableNetwork: () => (/* binding */ enableNetwork),\n/* harmony export */ enablePersistentCacheIndexAutoCreation: () => (/* binding */ enablePersistentCacheIndexAutoCreation),\n/* harmony export */ endAt: () => (/* binding */ endAt),\n/* harmony export */ endBefore: () => (/* binding */ endBefore),\n/* harmony export */ ensureFirestoreConfigured: () => (/* binding */ ensureFirestoreConfigured),\n/* harmony export */ executeWrite: () => (/* binding */ executeWrite),\n/* harmony export */ getAggregateFromServer: () => (/* binding */ getAggregateFromServer),\n/* harmony export */ getCountFromServer: () => (/* binding */ getCountFromServer),\n/* harmony export */ getDoc: () => (/* binding */ getDoc),\n/* harmony export */ getDocFromCache: () => (/* binding */ getDocFromCache),\n/* harmony export */ getDocFromServer: () => (/* binding */ getDocFromServer),\n/* harmony export */ getDocs: () => (/* binding */ getDocs),\n/* harmony export */ getDocsFromCache: () => (/* binding */ getDocsFromCache),\n/* harmony export */ getDocsFromServer: () => (/* binding */ getDocsFromServer),\n/* harmony export */ getFirestore: () => (/* binding */ getFirestore),\n/* harmony export */ getPersistentCacheIndexManager: () => (/* binding */ getPersistentCacheIndexManager),\n/* harmony export */ increment: () => (/* binding */ increment),\n/* harmony export */ initializeFirestore: () => (/* binding */ initializeFirestore),\n/* harmony export */ limit: () => (/* binding */ limit),\n/* harmony export */ limitToLast: () => (/* binding */ limitToLast),\n/* harmony export */ loadBundle: () => (/* binding */ loadBundle),\n/* harmony export */ memoryEagerGarbageCollector: () => (/* binding */ memoryEagerGarbageCollector),\n/* harmony export */ memoryLocalCache: () => (/* binding */ memoryLocalCache),\n/* harmony export */ memoryLruGarbageCollector: () => (/* binding */ memoryLruGarbageCollector),\n/* harmony export */ namedQuery: () => (/* binding */ namedQuery),\n/* harmony export */ onSnapshot: () => (/* binding */ onSnapshot),\n/* harmony export */ onSnapshotsInSync: () => (/* binding */ onSnapshotsInSync),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ orderBy: () => (/* binding */ orderBy),\n/* harmony export */ persistentLocalCache: () => (/* binding */ persistentLocalCache),\n/* harmony export */ persistentMultipleTabManager: () => (/* binding */ persistentMultipleTabManager),\n/* harmony export */ persistentSingleTabManager: () => (/* binding */ persistentSingleTabManager),\n/* harmony export */ query: () => (/* binding */ query),\n/* harmony export */ queryEqual: () => (/* binding */ queryEqual),\n/* harmony export */ refEqual: () => (/* binding */ refEqual),\n/* harmony export */ runTransaction: () => (/* binding */ runTransaction),\n/* harmony export */ serverTimestamp: () => (/* binding */ serverTimestamp),\n/* harmony export */ setDoc: () => (/* binding */ setDoc),\n/* harmony export */ setIndexConfiguration: () => (/* binding */ setIndexConfiguration),\n/* harmony export */ setLogLevel: () => (/* binding */ setLogLevel),\n/* harmony export */ snapshotEqual: () => (/* binding */ snapshotEqual),\n/* harmony export */ startAfter: () => (/* binding */ startAfter),\n/* harmony export */ startAt: () => (/* binding */ startAt),\n/* harmony export */ sum: () => (/* binding */ sum),\n/* harmony export */ terminate: () => (/* binding */ terminate),\n/* harmony export */ updateDoc: () => (/* binding */ updateDoc),\n/* harmony export */ waitForPendingWrites: () => (/* binding */ waitForPendingWrites),\n/* harmony export */ where: () => (/* binding */ where),\n/* harmony export */ writeBatch: () => (/* binding */ writeBatch)\n/* harmony export */ });\n/* harmony import */ var _firebase_app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @firebase/app */ \"./node_modules/@firebase/app/dist/esm/index.esm2017.js\");\n/* harmony import */ var _firebase_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @firebase/component */ \"./node_modules/@firebase/component/dist/esm/index.esm2017.js\");\n/* harmony import */ var _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @firebase/logger */ \"./node_modules/@firebase/logger/dist/esm/index.esm2017.js\");\n/* harmony import */ var _firebase_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @firebase/util */ \"./node_modules/@firebase/util/dist/index.esm2017.js\");\n/* harmony import */ var _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @firebase/webchannel-wrapper */ \"./node_modules/@firebase/webchannel-wrapper/dist/esm/index.esm2017.js\");\n\n\n\n\n\n\nconst w = \"@firebase/firestore\";\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 * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nclass User {\n constructor(e) {\n this.uid = e;\n }\n isAuthenticated() {\n return null != this.uid;\n }\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */ toKey() {\n return this.isAuthenticated() ? \"uid:\" + this.uid : \"anonymous-user\";\n }\n isEqual(e) {\n return e.uid === this.uid;\n }\n}\n\n/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), \n// TODO(mikelehen): Look into getting a proper uid-equivalent for\n// non-FirebaseAuth providers.\nUser.GOOGLE_CREDENTIALS = new User(\"google-credentials-uid\"), User.FIRST_PARTY = new User(\"first-party-uid\"), \nUser.MOCK_USER = new User(\"mock-user\");\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 */\nlet S = \"10.9.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 */\nconst b = new _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.Logger(\"@firebase/firestore\");\n\n// Helper methods are needed because variables can't be exported as read/write\nfunction __PRIVATE_getLogLevel() {\n return b.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 *
\n *
`debug` for the most verbose logging level, primarily for\n * debugging.
\n *
`error` to log errors only.
\n *
`silent` to turn off logging.
\n *
\n */ function setLogLevel(e) {\n b.setLogLevel(e);\n}\n\nfunction __PRIVATE_logDebug(e, ...t) {\n if (b.logLevel <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.DEBUG) {\n const n = t.map(__PRIVATE_argToString);\n b.debug(`Firestore (${S}): ${e}`, ...n);\n }\n}\n\nfunction __PRIVATE_logError(e, ...t) {\n if (b.logLevel <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.ERROR) {\n const n = t.map(__PRIVATE_argToString);\n b.error(`Firestore (${S}): ${e}`, ...n);\n }\n}\n\n/**\n * @internal\n */ function __PRIVATE_logWarn(e, ...t) {\n if (b.logLevel <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.WARN) {\n const n = t.map(__PRIVATE_argToString);\n b.warn(`Firestore (${S}): ${e}`, ...n);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */ function __PRIVATE_argToString(e) {\n if (\"string\" == typeof e) return e;\n try {\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /** Formats an object as a JSON string, suitable for logging. */\n return function __PRIVATE_formatJSON(e) {\n return JSON.stringify(e);\n }(e);\n } catch (t) {\n // Converting to JSON failed, just log the object directly\n return e;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */ function fail(e = \"Unexpected state\") {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const t = `FIRESTORE (${S}) INTERNAL ASSERTION FAILED: ` + e;\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw __PRIVATE_logError(t), new Error(t);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */ function __PRIVATE_hardAssert(e, t) {\n e || fail();\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */ function __PRIVATE_debugAssert(e, t) {\n e || fail();\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */ function __PRIVATE_debugCast(e, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nt) {\n return e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const D = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: \"ok\",\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: \"cancelled\",\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: \"unknown\",\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: \"invalid-argument\",\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: \"deadline-exceeded\",\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: \"not-found\",\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: \"already-exists\",\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: \"permission-denied\",\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: \"unauthenticated\",\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: \"resource-exhausted\",\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: \"failed-precondition\",\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: \"aborted\",\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: \"out-of-range\",\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: \"unimplemented\",\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: \"internal\",\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: \"unavailable\",\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: \"data-loss\"\n};\n\n/** An error returned by a Firestore operation. */ class FirestoreError extends _firebase_util__WEBPACK_IMPORTED_MODULE_3__.FirebaseError {\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n e, \n /**\n * A custom error description.\n */\n t) {\n super(e, t), this.code = e, this.message = t, \n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_Deferred {\n constructor() {\n this.promise = new Promise(((e, t) => {\n this.resolve = e, this.reject = t;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_OAuthToken {\n constructor(e, t) {\n this.user = t, this.type = \"OAuth\", this.headers = new Map, this.headers.set(\"Authorization\", `Bearer ${e}`);\n }\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */ class __PRIVATE_EmptyAuthCredentialsProvider {\n getToken() {\n return Promise.resolve(null);\n }\n invalidateToken() {}\n start(e, t) {\n // Fire with initial user.\n e.enqueueRetryable((() => t(User.UNAUTHENTICATED)));\n }\n shutdown() {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */ class __PRIVATE_EmulatorAuthCredentialsProvider {\n constructor(e) {\n this.token = e, \n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n this.changeListener = null;\n }\n getToken() {\n return Promise.resolve(this.token);\n }\n invalidateToken() {}\n start(e, t) {\n this.changeListener = t, \n // Fire with initial user.\n e.enqueueRetryable((() => t(this.token.user)));\n }\n shutdown() {\n this.changeListener = null;\n }\n}\n\nclass __PRIVATE_FirebaseAuthCredentialsProvider {\n constructor(e) {\n this.t = e, \n /** Tracks the current User. */\n this.currentUser = User.UNAUTHENTICATED, \n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n this.i = 0, this.forceRefresh = !1, this.auth = null;\n }\n start(e, t) {\n let n = this.i;\n // A change listener that prevents double-firing for the same token change.\n const __PRIVATE_guardedChangeListener = e => this.i !== n ? (n = this.i, \n t(e)) : Promise.resolve();\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let r = new __PRIVATE_Deferred;\n this.o = () => {\n this.i++, this.currentUser = this.u(), r.resolve(), r = new __PRIVATE_Deferred, \n e.enqueueRetryable((() => __PRIVATE_guardedChangeListener(this.currentUser)));\n };\n const __PRIVATE_awaitNextToken = () => {\n const t = r;\n e.enqueueRetryable((async () => {\n await t.promise, await __PRIVATE_guardedChangeListener(this.currentUser);\n }));\n }, __PRIVATE_registerAuth = e => {\n __PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"Auth detected\"), this.auth = e, \n this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken();\n };\n this.t.onInit((e => __PRIVATE_registerAuth(e))), \n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout((() => {\n if (!this.auth) {\n const e = this.t.getImmediate({\n optional: !0\n });\n e ? __PRIVATE_registerAuth(e) : (\n // If auth is still not available, proceed with `null` user\n __PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"Auth not yet detected\"), \n r.resolve(), r = new __PRIVATE_Deferred);\n }\n }), 0), __PRIVATE_awaitNextToken();\n }\n getToken() {\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const e = this.i, t = this.forceRefresh;\n return this.forceRefresh = !1, this.auth ? this.auth.getToken(t).then((t => \n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n this.i !== e ? (__PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"getToken aborted due to token change.\"), \n this.getToken()) : t ? (__PRIVATE_hardAssert(\"string\" == typeof t.accessToken), \n new __PRIVATE_OAuthToken(t.accessToken, this.currentUser)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.auth && this.auth.removeAuthTokenListener(this.o);\n }\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n u() {\n const e = this.auth && this.auth.getUid();\n return __PRIVATE_hardAssert(null === e || \"string\" == typeof e), new User(e);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */ class __PRIVATE_FirstPartyToken {\n constructor(e, t, n) {\n this.l = e, this.h = t, this.P = n, this.type = \"FirstParty\", this.user = User.FIRST_PARTY, \n this.I = new Map;\n }\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */ T() {\n return this.P ? this.P() : null;\n }\n get headers() {\n this.I.set(\"X-Goog-AuthUser\", this.l);\n // Use array notation to prevent minification\n const e = this.T();\n return e && this.I.set(\"Authorization\", e), this.h && this.I.set(\"X-Goog-Iam-Authorization-Token\", this.h), \n this.I;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */ class __PRIVATE_FirstPartyAuthCredentialsProvider {\n constructor(e, t, n) {\n this.l = e, this.h = t, this.P = n;\n }\n getToken() {\n return Promise.resolve(new __PRIVATE_FirstPartyToken(this.l, this.h, this.P));\n }\n start(e, t) {\n // Fire with initial uid.\n e.enqueueRetryable((() => t(User.FIRST_PARTY)));\n }\n shutdown() {}\n invalidateToken() {}\n}\n\nclass AppCheckToken {\n constructor(e) {\n this.value = e, this.type = \"AppCheck\", this.headers = new Map, e && e.length > 0 && this.headers.set(\"x-firebase-appcheck\", this.value);\n }\n}\n\nclass __PRIVATE_FirebaseAppCheckTokenProvider {\n constructor(e) {\n this.A = e, this.forceRefresh = !1, this.appCheck = null, this.R = null;\n }\n start(e, t) {\n const onTokenChanged = e => {\n null != e.error && __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", `Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);\n const n = e.token !== this.R;\n return this.R = e.token, __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", `Received ${n ? \"new\" : \"existing\"} token.`), \n n ? t(e.token) : Promise.resolve();\n };\n this.o = t => {\n e.enqueueRetryable((() => onTokenChanged(t)));\n };\n const __PRIVATE_registerAppCheck = e => {\n __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", \"AppCheck detected\"), this.appCheck = e, \n this.appCheck.addTokenListener(this.o);\n };\n this.A.onInit((e => __PRIVATE_registerAppCheck(e))), \n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout((() => {\n if (!this.appCheck) {\n const e = this.A.getImmediate({\n optional: !0\n });\n e ? __PRIVATE_registerAppCheck(e) : \n // If AppCheck is still not available, proceed without it.\n __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", \"AppCheck not yet detected\");\n }\n }), 0);\n }\n getToken() {\n const e = this.forceRefresh;\n return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(e).then((e => e ? (__PRIVATE_hardAssert(\"string\" == typeof e.token), \n this.R = e.token, new AppCheckToken(e.token)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.appCheck && this.appCheck.removeTokenListener(this.o);\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */ class __PRIVATE_EmptyAppCheckTokenProvider {\n getToken() {\n return Promise.resolve(new AppCheckToken(\"\"));\n }\n invalidateToken() {}\n start(e, t) {}\n shutdown() {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nfunction __PRIVATE_randomBytes(e) {\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const t = \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n \"undefined\" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(e);\n if (t && \"function\" == typeof t.getRandomValues) t.getRandomValues(n); else \n // Falls back to Math.random\n for (let t = 0; t < e; t++) n[t] = Math.floor(256 * Math.random());\n return n;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */ class __PRIVATE_AutoId {\n static newId() {\n // Alphanumeric characters\n const e = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", t = Math.floor(256 / e.length) * e.length;\n // The largest byte value that is a multiple of `char.length`.\n let n = \"\";\n for (;n.length < 20; ) {\n const r = __PRIVATE_randomBytes(40);\n for (let i = 0; i < r.length; ++i) \n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n n.length < 20 && r[i] < t && (n += e.charAt(r[i] % e.length));\n }\n return n;\n }\n}\n\nfunction __PRIVATE_primitiveComparator(e, t) {\n return e < t ? -1 : e > t ? 1 : 0;\n}\n\n/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(e, t, n) {\n return e.length === t.length && e.every(((e, r) => n(e, t[r])));\n}\n\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */ function __PRIVATE_immediateSuccessor(e) {\n // Return the input string, with an additional NUL byte appended.\n return e + \"\\0\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nclass Timestamp {\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n e, \n /**\n * The fractions of a second at nanosecond resolution.*\n */\n t) {\n if (this.seconds = e, this.nanoseconds = t, t < 0) throw new FirestoreError(D.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + t);\n if (t >= 1e9) throw new FirestoreError(D.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + t);\n if (e < -62135596800) throw new FirestoreError(D.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + e);\n // This will break in the year 10,000.\n if (e >= 253402300800) throw new FirestoreError(D.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + e);\n }\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */ static now() {\n return Timestamp.fromMillis(Date.now());\n }\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */ static fromDate(e) {\n return Timestamp.fromMillis(e.getTime());\n }\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */ static fromMillis(e) {\n const t = Math.floor(e / 1e3), n = Math.floor(1e6 * (e - 1e3 * t));\n return new Timestamp(t, n);\n }\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */ toDate() {\n return new Date(this.toMillis());\n }\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */ toMillis() {\n return 1e3 * this.seconds + this.nanoseconds / 1e6;\n }\n _compareTo(e) {\n return this.seconds === e.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e.seconds);\n }\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */ isEqual(e) {\n return e.seconds === this.seconds && e.nanoseconds === this.nanoseconds;\n }\n /** Returns a textual representation of this `Timestamp`. */ toString() {\n return \"Timestamp(seconds=\" + this.seconds + \", nanoseconds=\" + this.nanoseconds + \")\";\n }\n /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {\n return {\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */ valueOf() {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const e = this.seconds - -62135596800;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n return String(e).padStart(12, \"0\") + \".\" + String(this.nanoseconds).padStart(9, \"0\");\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */ class SnapshotVersion {\n constructor(e) {\n this.timestamp = e;\n }\n static fromTimestamp(e) {\n return new SnapshotVersion(e);\n }\n static min() {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n static max() {\n return new SnapshotVersion(new Timestamp(253402300799, 999999999));\n }\n compareTo(e) {\n return this.timestamp._compareTo(e.timestamp);\n }\n isEqual(e) {\n return this.timestamp.isEqual(e.timestamp);\n }\n /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {\n // Convert to microseconds.\n return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;\n }\n toString() {\n return \"SnapshotVersion(\" + this.timestamp.toString() + \")\";\n }\n toTimestamp() {\n return this.timestamp;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Path represents an ordered sequence of string segments.\n */\nclass BasePath {\n constructor(e, t, n) {\n void 0 === t ? t = 0 : t > e.length && fail(), void 0 === n ? n = e.length - t : n > e.length - t && fail(), \n this.segments = e, this.offset = t, this.len = n;\n }\n get length() {\n return this.len;\n }\n isEqual(e) {\n return 0 === BasePath.comparator(this, e);\n }\n child(e) {\n const t = this.segments.slice(this.offset, this.limit());\n return e instanceof BasePath ? e.forEach((e => {\n t.push(e);\n })) : t.push(e), this.construct(t);\n }\n /** The index of one past the last segment of the path. */ limit() {\n return this.offset + this.length;\n }\n popFirst(e) {\n return e = void 0 === e ? 1 : e, this.construct(this.segments, this.offset + e, this.length - e);\n }\n popLast() {\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n firstSegment() {\n return this.segments[this.offset];\n }\n lastSegment() {\n return this.get(this.length - 1);\n }\n get(e) {\n return this.segments[this.offset + e];\n }\n isEmpty() {\n return 0 === this.length;\n }\n isPrefixOf(e) {\n if (e.length < this.length) return !1;\n for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1;\n return !0;\n }\n isImmediateParentOf(e) {\n if (this.length + 1 !== e.length) return !1;\n for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1;\n return !0;\n }\n forEach(e) {\n for (let t = this.offset, n = this.limit(); t < n; t++) e(this.segments[t]);\n }\n toArray() {\n return this.segments.slice(this.offset, this.limit());\n }\n static comparator(e, t) {\n const n = Math.min(e.length, t.length);\n for (let r = 0; r < n; r++) {\n const n = e.get(r), i = t.get(r);\n if (n < i) return -1;\n if (n > i) return 1;\n }\n return e.length < t.length ? -1 : e.length > t.length ? 1 : 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */ class ResourcePath extends BasePath {\n construct(e, t, n) {\n return new ResourcePath(e, t, n);\n }\n canonicalString() {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n return this.toArray().join(\"/\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */ toUriEncodedString() {\n return this.toArray().map(encodeURIComponent).join(\"/\");\n }\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */ static fromString(...e) {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n const t = [];\n for (const n of e) {\n if (n.indexOf(\"//\") >= 0) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);\n // Strip leading and traling slashed.\n t.push(...n.split(\"/\").filter((e => e.length > 0)));\n }\n return new ResourcePath(t);\n }\n static emptyPath() {\n return new ResourcePath([]);\n }\n}\n\nconst C = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */ class FieldPath$1 extends BasePath {\n construct(e, t, n) {\n return new FieldPath$1(e, t, n);\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */ static isValidIdentifier(e) {\n return C.test(e);\n }\n canonicalString() {\n return this.toArray().map((e => (e = e.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\"), \n FieldPath$1.isValidIdentifier(e) || (e = \"`\" + e + \"`\"), e))).join(\".\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Returns true if this field references the key of a document.\n */ isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }\n /**\n * The field designating the key of a document.\n */ static keyField() {\n return new FieldPath$1([ \"__name__\" ]);\n }\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */ static fromServerFormat(e) {\n const t = [];\n let n = \"\", r = 0;\n const __PRIVATE_addCurrentSegment = () => {\n if (0 === n.length) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);\n t.push(n), n = \"\";\n };\n let i = !1;\n for (;r < e.length; ) {\n const t = e[r];\n if (\"\\\\\" === t) {\n if (r + 1 === e.length) throw new FirestoreError(D.INVALID_ARGUMENT, \"Path has trailing escape character: \" + e);\n const t = e[r + 1];\n if (\"\\\\\" !== t && \".\" !== t && \"`\" !== t) throw new FirestoreError(D.INVALID_ARGUMENT, \"Path has invalid escape sequence: \" + e);\n n += t, r += 2;\n } else \"`\" === t ? (i = !i, r++) : \".\" !== t || i ? (n += t, r++) : (__PRIVATE_addCurrentSegment(), \n r++);\n }\n if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(D.INVALID_ARGUMENT, \"Unterminated ` in path: \" + e);\n return new FieldPath$1(t);\n }\n static emptyPath() {\n return new FieldPath$1([]);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */ class DocumentKey {\n constructor(e) {\n this.path = e;\n }\n static fromPath(e) {\n return new DocumentKey(ResourcePath.fromString(e));\n }\n static fromName(e) {\n return new DocumentKey(ResourcePath.fromString(e).popFirst(5));\n }\n static empty() {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n get collectionGroup() {\n return this.path.popLast().lastSegment();\n }\n /** Returns true if the document is in the specified collectionId. */ hasCollectionId(e) {\n return this.path.length >= 2 && this.path.get(this.path.length - 2) === e;\n }\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {\n return this.path.get(this.path.length - 2);\n }\n /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {\n return this.path.popLast();\n }\n isEqual(e) {\n return null !== e && 0 === ResourcePath.comparator(this.path, e.path);\n }\n toString() {\n return this.path.toString();\n }\n static comparator(e, t) {\n return ResourcePath.comparator(e.path, t.path);\n }\n static isDocumentKey(e) {\n return e.length % 2 == 0;\n }\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */ static fromSegments(e) {\n return new DocumentKey(new ResourcePath(e.slice()));\n }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nclass FieldIndex {\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n e, \n /** The collection ID this index applies to. */\n t, \n /** The field segments for this index. */\n n, \n /** Shows how up-to-date the index is for the current user. */\n r) {\n this.indexId = e, this.collectionGroup = t, this.fields = n, this.indexState = r;\n }\n}\n\n/** An ID for an index that has not yet been added to persistence. */\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nfunction __PRIVATE_fieldIndexGetArraySegment(e) {\n return e.fields.find((e => 2 /* IndexKind.CONTAINS */ === e.kind));\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */ function __PRIVATE_fieldIndexGetDirectionalSegments(e) {\n return e.fields.filter((e => 2 /* IndexKind.CONTAINS */ !== e.kind));\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nfunction __PRIVATE_fieldIndexSemanticComparator(e, t) {\n let n = __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);\n if (0 !== n) return n;\n for (let r = 0; r < Math.min(e.fields.length, t.fields.length); ++r) if (n = __PRIVATE_indexSegmentComparator(e.fields[r], t.fields[r]), \n 0 !== n) return n;\n return __PRIVATE_primitiveComparator(e.fields.length, t.fields.length);\n}\n\n/** Returns a debug representation of the field index */ FieldIndex.UNKNOWN_ID = -1;\n\n/** An index component consisting of field path and index type. */\nclass IndexSegment {\n constructor(\n /** The field path of the component. */\n e, \n /** The fields sorting order. */\n t) {\n this.fieldPath = e, this.kind = t;\n }\n}\n\nfunction __PRIVATE_indexSegmentComparator(e, t) {\n const n = FieldPath$1.comparator(e.fieldPath, t.fieldPath);\n return 0 !== n ? n : __PRIVATE_primitiveComparator(e.kind, t.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */ class IndexState {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n e, \n /** The the latest indexed read time, document and batch id. */\n t) {\n this.sequenceNumber = e, this.offset = t;\n }\n /** The state of an index that has not yet been backfilled. */ static empty() {\n return new IndexState(0, IndexOffset.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */ function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e, t) {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const n = e.toTimestamp().seconds, r = e.toTimestamp().nanoseconds + 1, i = SnapshotVersion.fromTimestamp(1e9 === r ? new Timestamp(n + 1, 0) : new Timestamp(n, r));\n return new IndexOffset(i, DocumentKey.empty(), t);\n}\n\n/** Creates a new offset based on the provided document. */ function __PRIVATE_newIndexOffsetFromDocument(e) {\n return new IndexOffset(e.readTime, e.key, -1);\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */ class IndexOffset {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n e, \n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n t, \n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n n) {\n this.readTime = e, this.documentKey = t, this.largestBatchId = n;\n }\n /** Returns an offset that sorts before all regular offsets. */ static min() {\n return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), -1);\n }\n /** Returns an offset that sorts after all regular offsets. */ static max() {\n return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), -1);\n }\n}\n\nfunction __PRIVATE_indexOffsetComparator(e, t) {\n let n = e.readTime.compareTo(t.readTime);\n return 0 !== n ? n : (n = DocumentKey.comparator(e.documentKey, t.documentKey), \n 0 !== n ? n : __PRIVATE_primitiveComparator(e.largestBatchId, t.largestBatchId));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const v = \"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.\";\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */ class PersistenceTransaction {\n constructor() {\n this.onCommittedListeners = [];\n }\n addOnCommittedListener(e) {\n this.onCommittedListeners.push(e);\n }\n raiseOnCommittedEvent() {\n this.onCommittedListeners.forEach((e => e()));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */ async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e) {\n if (e.code !== D.FAILED_PRECONDITION || e.message !== v) throw e;\n __PRIVATE_logDebug(\"LocalStore\", \"Unexpectedly lost primary lease\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */ class PersistencePromise {\n constructor(e) {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n this.nextCallback = null, this.catchCallback = null, \n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = void 0, this.error = void 0, this.isDone = !1, \n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = !1, e((e => {\n this.isDone = !0, this.result = e, this.nextCallback && \n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(e);\n }), (e => {\n this.isDone = !0, this.error = e, this.catchCallback && this.catchCallback(e);\n }));\n }\n catch(e) {\n return this.next(void 0, e);\n }\n next(e, t) {\n return this.callbackAttached && fail(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(t, this.error) : this.wrapSuccess(e, this.result) : new PersistencePromise(((n, r) => {\n this.nextCallback = t => {\n this.wrapSuccess(e, t).next(n, r);\n }, this.catchCallback = e => {\n this.wrapFailure(t, e).next(n, r);\n };\n }));\n }\n toPromise() {\n return new Promise(((e, t) => {\n this.next(e, t);\n }));\n }\n wrapUserFunction(e) {\n try {\n const t = e();\n return t instanceof PersistencePromise ? t : PersistencePromise.resolve(t);\n } catch (e) {\n return PersistencePromise.reject(e);\n }\n }\n wrapSuccess(e, t) {\n return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.resolve(t);\n }\n wrapFailure(e, t) {\n return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.reject(t);\n }\n static resolve(e) {\n return new PersistencePromise(((t, n) => {\n t(e);\n }));\n }\n static reject(e) {\n return new PersistencePromise(((t, n) => {\n n(e);\n }));\n }\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n e) {\n return new PersistencePromise(((t, n) => {\n let r = 0, i = 0, s = !1;\n e.forEach((e => {\n ++r, e.next((() => {\n ++i, s && i === r && t();\n }), (e => n(e)));\n })), s = !0, i === r && t();\n }));\n }\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */ static or(e) {\n let t = PersistencePromise.resolve(!1);\n for (const n of e) t = t.next((e => e ? PersistencePromise.resolve(e) : n()));\n return t;\n }\n static forEach(e, t) {\n const n = [];\n return e.forEach(((e, r) => {\n n.push(t.call(this, e, r));\n })), this.waitFor(n);\n }\n /**\n * Concurrently map all array elements through asynchronous function.\n */ static mapArray(e, t) {\n return new PersistencePromise(((n, r) => {\n const i = e.length, s = new Array(i);\n let o = 0;\n for (let _ = 0; _ < i; _++) {\n const a = _;\n t(e[a]).next((e => {\n s[a] = e, ++o, o === i && n(s);\n }), (e => r(e)));\n }\n }));\n }\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */ static doWhile(e, t) {\n return new PersistencePromise(((n, r) => {\n const process = () => {\n !0 === e() ? t().next((() => {\n process();\n }), r) : n();\n };\n process();\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nclass __PRIVATE_SimpleDbTransaction {\n constructor(e, t) {\n this.action = e, this.transaction = t, this.aborted = !1, \n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n this.V = new __PRIVATE_Deferred, this.transaction.oncomplete = () => {\n this.V.resolve();\n }, this.transaction.onabort = () => {\n t.error ? this.V.reject(new __PRIVATE_IndexedDbTransactionError(e, t.error)) : this.V.resolve();\n }, this.transaction.onerror = t => {\n const n = __PRIVATE_checkForAndReportiOSError(t.target.error);\n this.V.reject(new __PRIVATE_IndexedDbTransactionError(e, n));\n };\n }\n static open(e, t, n, r) {\n try {\n return new __PRIVATE_SimpleDbTransaction(t, e.transaction(r, n));\n } catch (e) {\n throw new __PRIVATE_IndexedDbTransactionError(t, e);\n }\n }\n get m() {\n return this.V.promise;\n }\n abort(e) {\n e && this.V.reject(e), this.aborted || (__PRIVATE_logDebug(\"SimpleDb\", \"Aborting transaction:\", e ? e.message : \"Client-initiated abort\"), \n this.aborted = !0, this.transaction.abort());\n }\n g() {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = this.transaction;\n this.aborted || \"function\" != typeof e.commit || e.commit();\n }\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */ store(e) {\n const t = this.transaction.objectStore(e);\n return new __PRIVATE_SimpleDbStore(t);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */ class __PRIVATE_SimpleDb {\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(e, t, n) {\n this.name = e, this.version = t, this.p = n;\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n 12.2 === __PRIVATE_SimpleDb.S((0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getUA)()) && __PRIVATE_logError(\"Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.\");\n }\n /** Deletes the specified database. */ static delete(e) {\n return __PRIVATE_logDebug(\"SimpleDb\", \"Removing database:\", e), __PRIVATE_wrapRequest(window.indexedDB.deleteDatabase(e)).toPromise();\n }\n /** Returns true if IndexedDB is available in the current environment. */ static D() {\n if (!(0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.isIndexedDBAvailable)()) return !1;\n if (__PRIVATE_SimpleDb.C()) return !0;\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n // Check the UA string to find out the browser.\n const e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getUA)(), t = __PRIVATE_SimpleDb.S(e), n = 0 < t && t < 10, r = __PRIVATE_SimpleDb.v(e), i = 0 < r && r < 4.5;\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n // iOS Safari: Disable for users running iOS version < 10.\n return !(e.indexOf(\"MSIE \") > 0 || e.indexOf(\"Trident/\") > 0 || e.indexOf(\"Edge/\") > 0 || n || i);\n }\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */ static C() {\n var e;\n return \"undefined\" != typeof process && \"YES\" === (null === (e = process.__PRIVATE_env) || void 0 === e ? void 0 : e.F);\n }\n /** Helper to get a typed SimpleDbStore from a transaction. */ static M(e, t) {\n return e.store(t);\n }\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static S(e) {\n const t = e.match(/i(?:phone|pad|pod) os ([\\d_]+)/i), n = t ? t[1].split(\"_\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static v(e) {\n const t = e.match(/Android ([\\d.]+)/i), n = t ? t[1].split(\".\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */ async O(e) {\n return this.db || (__PRIVATE_logDebug(\"SimpleDb\", \"Opening database:\", this.name), \n this.db = await new Promise(((t, n) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const r = indexedDB.open(this.name, this.version);\n r.onsuccess = e => {\n const n = e.target.result;\n t(n);\n }, r.onblocked = () => {\n n(new __PRIVATE_IndexedDbTransactionError(e, \"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.\"));\n }, r.onerror = t => {\n const r = t.target.error;\n \"VersionError\" === r.name ? n(new FirestoreError(D.FAILED_PRECONDITION, \"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.\")) : \"InvalidStateError\" === r.name ? n(new FirestoreError(D.FAILED_PRECONDITION, \"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: \" + r)) : n(new __PRIVATE_IndexedDbTransactionError(e, r));\n }, r.onupgradeneeded = e => {\n __PRIVATE_logDebug(\"SimpleDb\", 'Database \"' + this.name + '\" requires upgrade from version:', e.oldVersion);\n const t = e.target.result;\n this.p.N(t, r.transaction, e.oldVersion, this.version).next((() => {\n __PRIVATE_logDebug(\"SimpleDb\", \"Database upgrade to version \" + this.version + \" complete\");\n }));\n };\n }))), this.L && (this.db.onversionchange = e => this.L(e)), this.db;\n }\n B(e) {\n this.L = e, this.db && (this.db.onversionchange = t => e(t));\n }\n async runTransaction(e, t, n, r) {\n const i = \"readonly\" === t;\n let s = 0;\n for (;;) {\n ++s;\n try {\n this.db = await this.O(e);\n const t = __PRIVATE_SimpleDbTransaction.open(this.db, e, i ? \"readonly\" : \"readwrite\", n), s = r(t).next((e => (t.g(), \n e))).catch((e => (\n // Abort the transaction if there was an error.\n t.abort(e), PersistencePromise.reject(e)))).toPromise();\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n return s.catch((() => {})), \n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await t.m, s;\n } catch (e) {\n const t = e, n = \"FirebaseError\" !== t.name && s < 3;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n if (__PRIVATE_logDebug(\"SimpleDb\", \"Transaction failed with error:\", t.message, \"Retrying:\", n), \n this.close(), !n) return Promise.reject(t);\n }\n }\n }\n close() {\n this.db && this.db.close(), this.db = void 0;\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */ class __PRIVATE_IterationController {\n constructor(e) {\n this.k = e, this.q = !1, this.K = null;\n }\n get isDone() {\n return this.q;\n }\n get $() {\n return this.K;\n }\n set cursor(e) {\n this.k = e;\n }\n /**\n * This function can be called to stop iteration at any point.\n */ done() {\n this.q = !0;\n }\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */ U(e) {\n this.K = e;\n }\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */ delete() {\n return __PRIVATE_wrapRequest(this.k.delete());\n }\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */ class __PRIVATE_IndexedDbTransactionError extends FirestoreError {\n constructor(e, t) {\n super(D.UNAVAILABLE, `IndexedDB transaction '${e}' failed: ${t}`), this.name = \"IndexedDbTransactionError\";\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */ function __PRIVATE_isIndexedDbTransactionError(e) {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return \"IndexedDbTransactionError\" === e.name;\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */ class __PRIVATE_SimpleDbStore {\n constructor(e) {\n this.store = e;\n }\n put(e, t) {\n let n;\n return void 0 !== t ? (__PRIVATE_logDebug(\"SimpleDb\", \"PUT\", this.store.name, e, t), \n n = this.store.put(t, e)) : (__PRIVATE_logDebug(\"SimpleDb\", \"PUT\", this.store.name, \"\", e), \n n = this.store.put(e)), __PRIVATE_wrapRequest(n);\n }\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */ add(e) {\n __PRIVATE_logDebug(\"SimpleDb\", \"ADD\", this.store.name, e, e);\n return __PRIVATE_wrapRequest(this.store.add(e));\n }\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */ get(e) {\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return __PRIVATE_wrapRequest(this.store.get(e)).next((t => (\n // Normalize nonexistence to null.\n void 0 === t && (t = null), __PRIVATE_logDebug(\"SimpleDb\", \"GET\", this.store.name, e, t), \n t)));\n }\n delete(e) {\n __PRIVATE_logDebug(\"SimpleDb\", \"DELETE\", this.store.name, e);\n return __PRIVATE_wrapRequest(this.store.delete(e));\n }\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */ count() {\n __PRIVATE_logDebug(\"SimpleDb\", \"COUNT\", this.store.name);\n return __PRIVATE_wrapRequest(this.store.count());\n }\n W(e, t) {\n const n = this.options(e, t), r = n.index ? this.store.index(n.index) : this.store;\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n if (\"function\" == typeof r.getAll) {\n const e = r.getAll(n.range);\n return new PersistencePromise(((t, n) => {\n e.onerror = e => {\n n(e.target.error);\n }, e.onsuccess = e => {\n t(e.target.result);\n };\n }));\n }\n {\n const e = this.cursor(n), t = [];\n return this.G(e, ((e, n) => {\n t.push(n);\n })).next((() => t));\n }\n }\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */ j(e, t) {\n const n = this.store.getAll(e, null === t ? void 0 : t);\n return new PersistencePromise(((e, t) => {\n n.onerror = e => {\n t(e.target.error);\n }, n.onsuccess = t => {\n e(t.target.result);\n };\n }));\n }\n H(e, t) {\n __PRIVATE_logDebug(\"SimpleDb\", \"DELETE ALL\", this.store.name);\n const n = this.options(e, t);\n n.J = !1;\n const r = this.cursor(n);\n return this.G(r, ((e, t, n) => n.delete()));\n }\n Y(e, t) {\n let n;\n t ? n = e : (n = {}, t = e);\n const r = this.cursor(n);\n return this.G(r, t);\n }\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */ Z(e) {\n const t = this.cursor({});\n return new PersistencePromise(((n, r) => {\n t.onerror = e => {\n const t = __PRIVATE_checkForAndReportiOSError(e.target.error);\n r(t);\n }, t.onsuccess = t => {\n const r = t.target.result;\n r ? e(r.primaryKey, r.value).next((e => {\n e ? r.continue() : n();\n })) : n();\n };\n }));\n }\n G(e, t) {\n const n = [];\n return new PersistencePromise(((r, i) => {\n e.onerror = e => {\n i(e.target.error);\n }, e.onsuccess = e => {\n const i = e.target.result;\n if (!i) return void r();\n const s = new __PRIVATE_IterationController(i), o = t(i.primaryKey, i.value, s);\n if (o instanceof PersistencePromise) {\n const e = o.catch((e => (s.done(), PersistencePromise.reject(e))));\n n.push(e);\n }\n s.isDone ? r() : null === s.$ ? i.continue() : i.continue(s.$);\n };\n })).next((() => PersistencePromise.waitFor(n)));\n }\n options(e, t) {\n let n;\n return void 0 !== e && (\"string\" == typeof e ? n = e : t = e), {\n index: n,\n range: t\n };\n }\n cursor(e) {\n let t = \"next\";\n if (e.reverse && (t = \"prev\"), e.index) {\n const n = this.store.index(e.index);\n return e.J ? n.openKeyCursor(e.range, t) : n.openCursor(e.range, t);\n }\n return this.store.openCursor(e.range, t);\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */ function __PRIVATE_wrapRequest(e) {\n return new PersistencePromise(((t, n) => {\n e.onsuccess = e => {\n const n = e.target.result;\n t(n);\n }, e.onerror = e => {\n const t = __PRIVATE_checkForAndReportiOSError(e.target.error);\n n(t);\n };\n }));\n}\n\n// Guard so we only report the error once.\nlet F = !1;\n\nfunction __PRIVATE_checkForAndReportiOSError(e) {\n const t = __PRIVATE_SimpleDb.S((0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getUA)());\n if (t >= 12.2 && t < 13) {\n const t = \"An internal error was encountered in the Indexed Database server\";\n if (e.message.indexOf(t) >= 0) {\n // Wrap error in a more descriptive one.\n const e = new FirestoreError(\"internal\", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);\n return F || (F = !0, \n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout((() => {\n throw e;\n }), 0)), e;\n }\n }\n return e;\n}\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nclass __PRIVATE_IndexBackfillerScheduler {\n constructor(e, t) {\n this.asyncQueue = e, this.X = t, this.task = null;\n }\n start() {\n this.ee(15e3);\n }\n stop() {\n this.task && (this.task.cancel(), this.task = null);\n }\n get started() {\n return null !== this.task;\n }\n ee(e) {\n __PRIVATE_logDebug(\"IndexBackfiller\", `Scheduled in ${e}ms`), this.task = this.asyncQueue.enqueueAfterDelay(\"index_backfill\" /* TimerId.IndexBackfill */ , e, (async () => {\n this.task = null;\n try {\n __PRIVATE_logDebug(\"IndexBackfiller\", `Documents written: ${await this.X.te()}`);\n } catch (e) {\n __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(\"IndexBackfiller\", \"Ignoring IndexedDB error during index backfill: \", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n }\n await this.ee(6e4);\n }));\n }\n}\n\n/** Implements the steps for backfilling indexes. */ class __PRIVATE_IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n e, t) {\n this.localStore = e, this.persistence = t;\n }\n async te(e = 50) {\n return this.persistence.runTransaction(\"Backfill Indexes\", \"readwrite-primary\", (t => this.ne(t, e)));\n }\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */ ne(e, t) {\n const n = new Set;\n let r = t, i = !0;\n return PersistencePromise.doWhile((() => !0 === i && r > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t => {\n if (null !== t && !n.has(t)) return __PRIVATE_logDebug(\"IndexBackfiller\", `Processing collection: ${t}`), \n this.re(e, t, r).next((e => {\n r -= e, n.add(t);\n }));\n i = !1;\n })))).next((() => t - r));\n }\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */ re(e, t, n) {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e, t).next((r => this.localStore.localDocuments.getNextDocuments(e, t, r, n).next((n => {\n const i = n.changes;\n return this.localStore.indexManager.updateIndexEntries(e, i).next((() => this.ie(r, n))).next((n => (__PRIVATE_logDebug(\"IndexBackfiller\", `Updating offset: ${n}`), \n this.localStore.indexManager.updateCollectionGroup(e, t, n)))).next((() => i.size));\n }))));\n }\n /** Returns the next offset based on the provided documents. */ ie(e, t) {\n let n = e;\n return t.changes.forEach(((e, t) => {\n const r = __PRIVATE_newIndexOffsetFromDocument(t);\n __PRIVATE_indexOffsetComparator(r, n) > 0 && (n = r);\n })), new IndexOffset(n.readTime, n.documentKey, Math.max(t.batchId, e.largestBatchId));\n }\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */ class __PRIVATE_ListenSequence {\n constructor(e, t) {\n this.previousValue = e, t && (t.sequenceNumberHandler = e => this.se(e), this.oe = e => t.writeSequenceNumber(e));\n }\n se(e) {\n return this.previousValue = Math.max(e, this.previousValue), this.previousValue;\n }\n next() {\n const e = ++this.previousValue;\n return this.oe && this.oe(e), e;\n }\n}\n\n__PRIVATE_ListenSequence._e = -1;\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction __PRIVATE_isNullOrUndefined(e) {\n return null == e;\n}\n\n/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(e) {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return 0 === e && 1 / e == -1 / 0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */ function isSafeInteger(e) {\n return \"number\" == typeof e && Number.isInteger(e) && !__PRIVATE_isNegativeZero(e) && e <= Number.MAX_SAFE_INTEGER && e >= Number.MIN_SAFE_INTEGER;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction __PRIVATE_encodeResourcePath(e) {\n let t = \"\";\n for (let n = 0; n < e.length; n++) t.length > 0 && (t = __PRIVATE_encodeSeparator(t)), \n t = __PRIVATE_encodeSegment(e.get(n), t);\n return __PRIVATE_encodeSeparator(t);\n}\n\n/** Encodes a single segment of a resource path into the given result */ function __PRIVATE_encodeSegment(e, t) {\n let n = t;\n const r = e.length;\n for (let t = 0; t < r; t++) {\n const r = e.charAt(t);\n switch (r) {\n case \"\\0\":\n n += \"\u0001\u0010\";\n break;\n\n case \"\u0001\":\n n += \"\u0001\u0011\";\n break;\n\n default:\n n += r;\n }\n }\n return n;\n}\n\n/** Encodes a path separator into the given result */ function __PRIVATE_encodeSeparator(e) {\n return e + \"\u0001\u0001\";\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */ function __PRIVATE_decodeResourcePath(e) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const t = e.length;\n if (__PRIVATE_hardAssert(t >= 2), 2 === t) return __PRIVATE_hardAssert(\"\u0001\" === e.charAt(0) && \"\u0001\" === e.charAt(1)), \n ResourcePath.emptyPath();\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const __PRIVATE_lastReasonableEscapeIndex = t - 2, n = [];\n let r = \"\";\n for (let i = 0; i < t; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const t = e.indexOf(\"\u0001\", i);\n (t < 0 || t > __PRIVATE_lastReasonableEscapeIndex) && fail();\n switch (e.charAt(t + 1)) {\n case \"\u0001\":\n const s = e.substring(i, t);\n let o;\n 0 === r.length ? \n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n o = s : (r += s, o = r, r = \"\"), n.push(o);\n break;\n\n case \"\u0010\":\n r += e.substring(i, t), r += \"\\0\";\n break;\n\n case \"\u0011\":\n // The escape character can be used in the output to encode itself.\n r += e.substring(i, t + 1);\n break;\n\n default:\n fail();\n }\n i = t + 2;\n }\n return new ResourcePath(n);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const M = [ \"userId\", \"batchId\" ];\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nfunction __PRIVATE_newDbDocumentMutationPrefixForPath(e, t) {\n return [ e, __PRIVATE_encodeResourcePath(t) ];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */ function __PRIVATE_newDbDocumentMutationKey(e, t, n) {\n return [ e, __PRIVATE_encodeResourcePath(t), n ];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */ const x = {}, O = [ \"prefixPath\", \"collectionGroup\", \"readTime\", \"documentId\" ], N = [ \"prefixPath\", \"collectionGroup\", \"documentId\" ], L = [ \"collectionGroup\", \"readTime\", \"prefixPath\", \"documentId\" ], B = [ \"canonicalId\", \"targetId\" ], k = [ \"targetId\", \"path\" ], q = [ \"path\", \"targetId\" ], Q = [ \"collectionId\", \"parent\" ], K = [ \"indexId\", \"uid\" ], $ = [ \"uid\", \"sequenceNumber\" ], U = [ \"indexId\", \"uid\", \"arrayValue\", \"directionalValue\", \"orderedDocumentKey\", \"documentKey\" ], W = [ \"indexId\", \"uid\", \"orderedDocumentKey\" ], G = [ \"userId\", \"collectionPath\", \"documentId\" ], z = [ \"userId\", \"collectionPath\", \"largestBatchId\" ], j = [ \"userId\", \"collectionGroup\", \"largestBatchId\" ], H = [ ...[ ...[ ...[ ...[ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocuments\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\" ], \"clientMetadata\" ], \"remoteDocumentGlobal\" ], \"collectionParents\" ], \"bundles\", \"namedQueries\" ], J = [ ...H, \"documentOverlays\" ], Y = [ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocumentsV14\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\", \"clientMetadata\", \"remoteDocumentGlobal\", \"collectionParents\", \"bundles\", \"namedQueries\", \"documentOverlays\" ], Z = Y, X = [ ...Z, \"indexConfiguration\", \"indexState\", \"indexEntries\" ];\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass __PRIVATE_IndexedDbTransaction extends PersistenceTransaction {\n constructor(e, t) {\n super(), this.ae = e, this.currentSequenceNumber = t;\n }\n}\n\nfunction __PRIVATE_getStore(e, t) {\n const n = __PRIVATE_debugCast(e);\n return __PRIVATE_SimpleDb.M(n.ae, t);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_objectSize(e) {\n let t = 0;\n for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t++;\n return t;\n}\n\nfunction forEach(e, t) {\n for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t(n, e[n]);\n}\n\nfunction isEmpty(e) {\n for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return !1;\n return !0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nclass SortedMap {\n constructor(e, t) {\n this.comparator = e, this.root = t || LLRBNode.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(e, t) {\n return new SortedMap(this.comparator, this.root.insert(e, t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));\n }\n // Returns a copy of the map, with the specified key removed.\n remove(e) {\n return new SortedMap(this.comparator, this.root.remove(e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));\n }\n // Returns the value of the node with the given key, or null.\n get(e) {\n let t = this.root;\n for (;!t.isEmpty(); ) {\n const n = this.comparator(e, t.key);\n if (0 === n) return t.value;\n n < 0 ? t = t.left : n > 0 && (t = t.right);\n }\n return null;\n }\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(e) {\n // Number of nodes that were pruned when descending right\n let t = 0, n = this.root;\n for (;!n.isEmpty(); ) {\n const r = this.comparator(e, n.key);\n if (0 === r) return t + n.left.size;\n r < 0 ? n = n.left : (\n // Count all nodes left of the node plus the node itself\n t += n.left.size + 1, n = n.right);\n }\n // Node not found\n return -1;\n }\n isEmpty() {\n return this.root.isEmpty();\n }\n // Returns the total number of nodes in the map.\n get size() {\n return this.root.size;\n }\n // Returns the minimum key in the map.\n minKey() {\n return this.root.minKey();\n }\n // Returns the maximum key in the map.\n maxKey() {\n return this.root.maxKey();\n }\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(e) {\n return this.root.inorderTraversal(e);\n }\n forEach(e) {\n this.inorderTraversal(((t, n) => (e(t, n), !1)));\n }\n toString() {\n const e = [];\n return this.inorderTraversal(((t, n) => (e.push(`${t}:${n}`), !1))), `{${e.join(\", \")}}`;\n }\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(e) {\n return this.root.reverseTraversal(e);\n }\n // Returns an iterator over the SortedMap.\n getIterator() {\n return new SortedMapIterator(this.root, null, this.comparator, !1);\n }\n getIteratorFrom(e) {\n return new SortedMapIterator(this.root, e, this.comparator, !1);\n }\n getReverseIterator() {\n return new SortedMapIterator(this.root, null, this.comparator, !0);\n }\n getReverseIteratorFrom(e) {\n return new SortedMapIterator(this.root, e, this.comparator, !0);\n }\n}\n\n // end SortedMap\n// An iterator over an LLRBNode.\nclass SortedMapIterator {\n constructor(e, t, n, r) {\n this.isReverse = r, this.nodeStack = [];\n let i = 1;\n for (;!e.isEmpty(); ) if (i = t ? n(e.key, t) : 1, \n // flip the comparison if we're going in reverse\n t && r && (i *= -1), i < 0) \n // This node is less than our start key. ignore it\n e = this.isReverse ? e.left : e.right; else {\n if (0 === i) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(e);\n break;\n }\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(e), e = this.isReverse ? e.right : e.left;\n }\n }\n getNext() {\n let e = this.nodeStack.pop();\n const t = {\n key: e.key,\n value: e.value\n };\n if (this.isReverse) for (e = e.left; !e.isEmpty(); ) this.nodeStack.push(e), e = e.right; else for (e = e.right; !e.isEmpty(); ) this.nodeStack.push(e), \n e = e.left;\n return t;\n }\n hasNext() {\n return this.nodeStack.length > 0;\n }\n peek() {\n if (0 === this.nodeStack.length) return null;\n const e = this.nodeStack[this.nodeStack.length - 1];\n return {\n key: e.key,\n value: e.value\n };\n }\n}\n\n // end SortedMapIterator\n// Represents a node in a Left-leaning Red-Black tree.\nclass LLRBNode {\n constructor(e, t, n, r, i) {\n this.key = e, this.value = t, this.color = null != n ? n : LLRBNode.RED, this.left = null != r ? r : LLRBNode.EMPTY, \n this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(e, t, n, r, i) {\n return new LLRBNode(null != e ? e : this.key, null != t ? t : this.value, null != n ? n : this.color, null != r ? r : this.left, null != i ? i : this.right);\n }\n isEmpty() {\n return !1;\n }\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(e) {\n return this.left.inorderTraversal(e) || e(this.key, this.value) || this.right.inorderTraversal(e);\n }\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(e) {\n return this.right.reverseTraversal(e) || e(this.key, this.value) || this.left.reverseTraversal(e);\n }\n // Returns the minimum node in the tree.\n min() {\n return this.left.isEmpty() ? this : this.left.min();\n }\n // Returns the maximum key in the tree.\n minKey() {\n return this.min().key;\n }\n // Returns the maximum key in the tree.\n maxKey() {\n return this.right.isEmpty() ? this.key : this.right.maxKey();\n }\n // Returns new tree, with the key/value added.\n insert(e, t, n) {\n let r = this;\n const i = n(e, r.key);\n return r = i < 0 ? r.copy(null, null, null, r.left.insert(e, t, n), null) : 0 === i ? r.copy(null, t, null, null, null) : r.copy(null, null, null, null, r.right.insert(e, t, n)), \n r.fixUp();\n }\n removeMin() {\n if (this.left.isEmpty()) return LLRBNode.EMPTY;\n let e = this;\n return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), e = e.copy(null, null, null, e.left.removeMin(), null), \n e.fixUp();\n }\n // Returns new tree, with the specified item removed.\n remove(e, t) {\n let n, r = this;\n if (t(e, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()), \n r = r.copy(null, null, null, r.left.remove(e, t), null); else {\n if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()), \n 0 === t(e, r.key)) {\n if (r.right.isEmpty()) return LLRBNode.EMPTY;\n n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin());\n }\n r = r.copy(null, null, null, null, r.right.remove(e, t));\n }\n return r.fixUp();\n }\n isRed() {\n return this.color;\n }\n // Returns new tree after performing any needed rotations.\n fixUp() {\n let e = this;\n return e.right.isRed() && !e.left.isRed() && (e = e.rotateLeft()), e.left.isRed() && e.left.left.isRed() && (e = e.rotateRight()), \n e.left.isRed() && e.right.isRed() && (e = e.colorFlip()), e;\n }\n moveRedLeft() {\n let e = this.colorFlip();\n return e.right.left.isRed() && (e = e.copy(null, null, null, null, e.right.rotateRight()), \n e = e.rotateLeft(), e = e.colorFlip()), e;\n }\n moveRedRight() {\n let e = this.colorFlip();\n return e.left.left.isRed() && (e = e.rotateRight(), e = e.colorFlip()), e;\n }\n rotateLeft() {\n const e = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, e, null);\n }\n rotateRight() {\n const e = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, e);\n }\n colorFlip() {\n const e = this.left.copy(null, null, !this.left.color, null, null), t = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, e, t);\n }\n // For testing.\n checkMaxDepth() {\n const e = this.check();\n return Math.pow(2, e) <= this.size + 1;\n }\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n check() {\n if (this.isRed() && this.left.isRed()) throw fail();\n if (this.right.isRed()) throw fail();\n const e = this.left.check();\n if (e !== this.right.check()) throw fail();\n return e + (this.isRed() ? 0 : 1);\n }\n}\n\n // end LLRBNode\n// Empty node is shared between all LLRB trees.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nLLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1;\n\n// end LLRBEmptyNode\nLLRBNode.EMPTY = new \n// Represents an empty node (a leaf node in the Red-Black Tree).\nclass LLRBEmptyNode {\n constructor() {\n this.size = 0;\n }\n get key() {\n throw fail();\n }\n get value() {\n throw fail();\n }\n get color() {\n throw fail();\n }\n get left() {\n throw fail();\n }\n get right() {\n throw fail();\n }\n // Returns a copy of the current node.\n copy(e, t, n, r, i) {\n return this;\n }\n // Returns a copy of the tree, with the specified key/value added.\n insert(e, t, n) {\n return new LLRBNode(e, t);\n }\n // Returns a copy of the tree, with the specified key removed.\n remove(e, t) {\n return this;\n }\n isEmpty() {\n return !0;\n }\n inorderTraversal(e) {\n return !1;\n }\n reverseTraversal(e) {\n return !1;\n }\n minKey() {\n return null;\n }\n maxKey() {\n return null;\n }\n isRed() {\n return !1;\n }\n // For testing.\n checkMaxDepth() {\n return !0;\n }\n check() {\n return 0;\n }\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nclass SortedSet {\n constructor(e) {\n this.comparator = e, this.data = new SortedMap(this.comparator);\n }\n has(e) {\n return null !== this.data.get(e);\n }\n first() {\n return this.data.minKey();\n }\n last() {\n return this.data.maxKey();\n }\n get size() {\n return this.data.size;\n }\n indexOf(e) {\n return this.data.indexOf(e);\n }\n /** Iterates elements in order defined by \"comparator\" */ forEach(e) {\n this.data.inorderTraversal(((t, n) => (e(t), !1)));\n }\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(e, t) {\n const n = this.data.getIteratorFrom(e[0]);\n for (;n.hasNext(); ) {\n const r = n.getNext();\n if (this.comparator(r.key, e[1]) >= 0) return;\n t(r.key);\n }\n }\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */ forEachWhile(e, t) {\n let n;\n for (n = void 0 !== t ? this.data.getIteratorFrom(t) : this.data.getIterator(); n.hasNext(); ) {\n if (!e(n.getNext().key)) return;\n }\n }\n /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(e) {\n const t = this.data.getIteratorFrom(e);\n return t.hasNext() ? t.getNext().key : null;\n }\n getIterator() {\n return new SortedSetIterator(this.data.getIterator());\n }\n getIteratorFrom(e) {\n return new SortedSetIterator(this.data.getIteratorFrom(e));\n }\n /** Inserts or updates an element */ add(e) {\n return this.copy(this.data.remove(e).insert(e, !0));\n }\n /** Deletes an element */ delete(e) {\n return this.has(e) ? this.copy(this.data.remove(e)) : this;\n }\n isEmpty() {\n return this.data.isEmpty();\n }\n unionWith(e) {\n let t = this;\n // Make sure `result` always refers to the larger one of the two sets.\n return t.size < e.size && (t = e, e = this), e.forEach((e => {\n t = t.add(e);\n })), t;\n }\n isEqual(e) {\n if (!(e instanceof SortedSet)) return !1;\n if (this.size !== e.size) return !1;\n const t = this.data.getIterator(), n = e.data.getIterator();\n for (;t.hasNext(); ) {\n const e = t.getNext().key, r = n.getNext().key;\n if (0 !== this.comparator(e, r)) return !1;\n }\n return !0;\n }\n toArray() {\n const e = [];\n return this.forEach((t => {\n e.push(t);\n })), e;\n }\n toString() {\n const e = [];\n return this.forEach((t => e.push(t))), \"SortedSet(\" + e.toString() + \")\";\n }\n copy(e) {\n const t = new SortedSet(this.comparator);\n return t.data = e, t;\n }\n}\n\nclass SortedSetIterator {\n constructor(e) {\n this.iter = e;\n }\n getNext() {\n return this.iter.getNext().key;\n }\n hasNext() {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction __PRIVATE_advanceIterator(e) {\n return e.hasNext() ? e.getNext() : void 0;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */ class FieldMask {\n constructor(e) {\n this.fields = e, \n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n e.sort(FieldPath$1.comparator);\n }\n static empty() {\n return new FieldMask([]);\n }\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */ unionWith(e) {\n let t = new SortedSet(FieldPath$1.comparator);\n for (const e of this.fields) t = t.add(e);\n for (const n of e) t = t.add(n);\n return new FieldMask(t.toArray());\n }\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */ covers(e) {\n for (const t of this.fields) if (t.isPrefixOf(e)) return !0;\n return !1;\n }\n isEqual(e) {\n return __PRIVATE_arrayEquals(this.fields, e.fields, ((e, t) => e.isEqual(t)));\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An error encountered while decoding base64 string.\n */ class __PRIVATE_Base64DecodeError extends Error {\n constructor() {\n super(...arguments), this.name = \"Base64DecodeError\";\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Converts a Base64 encoded string to a binary string. */\n/** True if and only if the Base64 conversion functions are available. */\nfunction __PRIVATE_isBase64Available() {\n return \"undefined\" != typeof atob;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */ class ByteString {\n constructor(e) {\n this.binaryString = e;\n }\n static fromBase64String(e) {\n const t = function __PRIVATE_decodeBase64(e) {\n try {\n return atob(e);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n throw \"undefined\" != typeof DOMException && e instanceof DOMException ? new __PRIVATE_Base64DecodeError(\"Invalid base64 string: \" + e) : e;\n }\n }\n /** Converts a binary string to a Base64 encoded string. */ (e);\n return new ByteString(t);\n }\n static fromUint8Array(e) {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const t = \n /**\n * Helper function to convert an Uint8array to a binary string.\n */\n function __PRIVATE_binaryStringFromUint8Array(e) {\n let t = \"\";\n for (let n = 0; n < e.length; ++n) t += String.fromCharCode(e[n]);\n return t;\n }\n /**\n * Helper function to convert a binary string to an Uint8Array.\n */ (e);\n return new ByteString(t);\n }\n [Symbol.iterator]() {\n let e = 0;\n return {\n next: () => e < this.binaryString.length ? {\n value: this.binaryString.charCodeAt(e++),\n done: !1\n } : {\n value: void 0,\n done: !0\n }\n };\n }\n toBase64() {\n return function __PRIVATE_encodeBase64(e) {\n return btoa(e);\n }(this.binaryString);\n }\n toUint8Array() {\n return function __PRIVATE_uint8ArrayFromBinaryString(e) {\n const t = new Uint8Array(e.length);\n for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n);\n return t;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\n (this.binaryString);\n }\n approximateByteSize() {\n return 2 * this.binaryString.length;\n }\n compareTo(e) {\n return __PRIVATE_primitiveComparator(this.binaryString, e.binaryString);\n }\n isEqual(e) {\n return this.binaryString === e.binaryString;\n }\n}\n\nByteString.EMPTY_BYTE_STRING = new ByteString(\"\");\n\nconst ee = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */ function __PRIVATE_normalizeTimestamp(e) {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (__PRIVATE_hardAssert(!!e), \"string\" == typeof e) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n let t = 0;\n const n = ee.exec(e);\n if (__PRIVATE_hardAssert(!!n), n[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let e = n[1];\n e = (e + \"000000000\").substr(0, 9), t = Number(e);\n }\n // Parse the date to get the seconds.\n const r = new Date(e);\n return {\n seconds: Math.floor(r.getTime() / 1e3),\n nanos: t\n };\n }\n return {\n seconds: __PRIVATE_normalizeNumber(e.seconds),\n nanos: __PRIVATE_normalizeNumber(e.nanos)\n };\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */ function __PRIVATE_normalizeNumber(e) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n return \"number\" == typeof e ? e : \"string\" == typeof e ? Number(e) : 0;\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(e) {\n return \"string\" == typeof e ? ByteString.fromBase64String(e) : ByteString.fromUint8Array(e);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */ function __PRIVATE_isServerTimestamp(e) {\n var t, n;\n return \"server_timestamp\" === (null === (n = ((null === (t = null == e ? void 0 : e.mapValue) || void 0 === t ? void 0 : t.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nfunction __PRIVATE_getPreviousValue(e) {\n const t = e.mapValue.fields.__previous_value__;\n return __PRIVATE_isServerTimestamp(t) ? __PRIVATE_getPreviousValue(t) : t;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */ function __PRIVATE_getLocalWriteTime(e) {\n const t = __PRIVATE_normalizeTimestamp(e.mapValue.fields.__local_write_time__.timestampValue);\n return new Timestamp(t.seconds, t.nanos);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(e, t, n, r, i, s, o, _, a) {\n this.databaseId = e, this.appId = t, this.persistenceKey = n, this.host = r, this.ssl = i, \n this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = _, \n this.useFetchStreams = a;\n }\n}\n\n/** The default database name for a project. */\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nclass DatabaseId {\n constructor(e, t) {\n this.projectId = e, this.database = t || \"(default)\";\n }\n static empty() {\n return new DatabaseId(\"\", \"\");\n }\n get isDefaultDatabase() {\n return \"(default)\" === this.database;\n }\n isEqual(e) {\n return e instanceof DatabaseId && e.projectId === this.projectId && e.database === this.database;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst te = {\n mapValue: {\n fields: {\n __type__: {\n stringValue: \"__max__\"\n }\n }\n }\n}, ne = {\n nullValue: \"NULL_VALUE\"\n};\n\n/** Extracts the backend's type order for the provided value. */\nfunction __PRIVATE_typeOrder(e) {\n return \"nullValue\" in e ? 0 /* TypeOrder.NullValue */ : \"booleanValue\" in e ? 1 /* TypeOrder.BooleanValue */ : \"integerValue\" in e || \"doubleValue\" in e ? 2 /* TypeOrder.NumberValue */ : \"timestampValue\" in e ? 3 /* TypeOrder.TimestampValue */ : \"stringValue\" in e ? 5 /* TypeOrder.StringValue */ : \"bytesValue\" in e ? 6 /* TypeOrder.BlobValue */ : \"referenceValue\" in e ? 7 /* TypeOrder.RefValue */ : \"geoPointValue\" in e ? 8 /* TypeOrder.GeoPointValue */ : \"arrayValue\" in e ? 9 /* TypeOrder.ArrayValue */ : \"mapValue\" in e ? __PRIVATE_isServerTimestamp(e) ? 4 /* TypeOrder.ServerTimestampValue */ : __PRIVATE_isMaxValue(e) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : fail();\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(e, t) {\n if (e === t) return !0;\n const n = __PRIVATE_typeOrder(e);\n if (n !== __PRIVATE_typeOrder(t)) return !1;\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return !0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return e.booleanValue === t.booleanValue;\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t));\n\n case 3 /* TypeOrder.TimestampValue */ :\n return function __PRIVATE_timestampEquals(e, t) {\n if (\"string\" == typeof e.timestampValue && \"string\" == typeof t.timestampValue && e.timestampValue.length === t.timestampValue.length) \n // Use string equality for ISO 8601 timestamps\n return e.timestampValue === t.timestampValue;\n const n = __PRIVATE_normalizeTimestamp(e.timestampValue), r = __PRIVATE_normalizeTimestamp(t.timestampValue);\n return n.seconds === r.seconds && n.nanos === r.nanos;\n }(e, t);\n\n case 5 /* TypeOrder.StringValue */ :\n return e.stringValue === t.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return function __PRIVATE_blobEquals(e, t) {\n return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(t.bytesValue));\n }(e, t);\n\n case 7 /* TypeOrder.RefValue */ :\n return e.referenceValue === t.referenceValue;\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function __PRIVATE_geoPointEquals(e, t) {\n return __PRIVATE_normalizeNumber(e.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t.geoPointValue.longitude);\n }(e, t);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function __PRIVATE_numberEquals(e, t) {\n if (\"integerValue\" in e && \"integerValue\" in t) return __PRIVATE_normalizeNumber(e.integerValue) === __PRIVATE_normalizeNumber(t.integerValue);\n if (\"doubleValue\" in e && \"doubleValue\" in t) {\n const n = __PRIVATE_normalizeNumber(e.doubleValue), r = __PRIVATE_normalizeNumber(t.doubleValue);\n return n === r ? __PRIVATE_isNegativeZero(n) === __PRIVATE_isNegativeZero(r) : isNaN(n) && isNaN(r);\n }\n return !1;\n }(e, t);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return __PRIVATE_arrayEquals(e.arrayValue.values || [], t.arrayValue.values || [], __PRIVATE_valueEquals);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function __PRIVATE_objectEquals(e, t) {\n const n = e.mapValue.fields || {}, r = t.mapValue.fields || {};\n if (__PRIVATE_objectSize(n) !== __PRIVATE_objectSize(r)) return !1;\n for (const e in n) if (n.hasOwnProperty(e) && (void 0 === r[e] || !__PRIVATE_valueEquals(n[e], r[e]))) return !1;\n return !0;\n }\n /** Returns true if the ArrayValue contains the specified element. */ (e, t);\n\n default:\n return fail();\n }\n}\n\nfunction __PRIVATE_arrayValueContains(e, t) {\n return void 0 !== (e.values || []).find((e => __PRIVATE_valueEquals(e, t)));\n}\n\nfunction __PRIVATE_valueCompare(e, t) {\n if (e === t) return 0;\n const n = __PRIVATE_typeOrder(e), r = __PRIVATE_typeOrder(t);\n if (n !== r) return __PRIVATE_primitiveComparator(n, r);\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return 0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return __PRIVATE_primitiveComparator(e.booleanValue, t.booleanValue);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function __PRIVATE_compareNumbers(e, t) {\n const n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue), r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue);\n return n < r ? -1 : n > r ? 1 : n === r ? 0 : \n // one or both are NaN.\n isNaN(n) ? isNaN(r) ? 0 : -1 : 1;\n }(e, t);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return __PRIVATE_compareTimestamps(e.timestampValue, t.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e), __PRIVATE_getLocalWriteTime(t));\n\n case 5 /* TypeOrder.StringValue */ :\n return __PRIVATE_primitiveComparator(e.stringValue, t.stringValue);\n\n case 6 /* TypeOrder.BlobValue */ :\n return function __PRIVATE_compareBlobs(e, t) {\n const n = __PRIVATE_normalizeByteString(e), r = __PRIVATE_normalizeByteString(t);\n return n.compareTo(r);\n }(e.bytesValue, t.bytesValue);\n\n case 7 /* TypeOrder.RefValue */ :\n return function __PRIVATE_compareReferences(e, t) {\n const n = e.split(\"/\"), r = t.split(\"/\");\n for (let e = 0; e < n.length && e < r.length; e++) {\n const t = __PRIVATE_primitiveComparator(n[e], r[e]);\n if (0 !== t) return t;\n }\n return __PRIVATE_primitiveComparator(n.length, r.length);\n }(e.referenceValue, t.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function __PRIVATE_compareGeoPoints(e, t) {\n const n = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(t.latitude));\n if (0 !== n) return n;\n return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude), __PRIVATE_normalizeNumber(t.longitude));\n }(e.geoPointValue, t.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return function __PRIVATE_compareArrays(e, t) {\n const n = e.values || [], r = t.values || [];\n for (let e = 0; e < n.length && e < r.length; ++e) {\n const t = __PRIVATE_valueCompare(n[e], r[e]);\n if (t) return t;\n }\n return __PRIVATE_primitiveComparator(n.length, r.length);\n }(e.arrayValue, t.arrayValue);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function __PRIVATE_compareMaps(e, t) {\n if (e === te.mapValue && t === te.mapValue) return 0;\n if (e === te.mapValue) return 1;\n if (t === te.mapValue) return -1;\n const n = e.fields || {}, r = Object.keys(n), i = t.fields || {}, s = Object.keys(i);\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n r.sort(), s.sort();\n for (let e = 0; e < r.length && e < s.length; ++e) {\n const t = __PRIVATE_primitiveComparator(r[e], s[e]);\n if (0 !== t) return t;\n const o = __PRIVATE_valueCompare(n[r[e]], i[s[e]]);\n if (0 !== o) return o;\n }\n return __PRIVATE_primitiveComparator(r.length, s.length);\n }\n /**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */ (e.mapValue, t.mapValue);\n\n default:\n throw fail();\n }\n}\n\nfunction __PRIVATE_compareTimestamps(e, t) {\n if (\"string\" == typeof e && \"string\" == typeof t && e.length === t.length) return __PRIVATE_primitiveComparator(e, t);\n const n = __PRIVATE_normalizeTimestamp(e), r = __PRIVATE_normalizeTimestamp(t), i = __PRIVATE_primitiveComparator(n.seconds, r.seconds);\n return 0 !== i ? i : __PRIVATE_primitiveComparator(n.nanos, r.nanos);\n}\n\nfunction canonicalId(e) {\n return __PRIVATE_canonifyValue(e);\n}\n\nfunction __PRIVATE_canonifyValue(e) {\n return \"nullValue\" in e ? \"null\" : \"booleanValue\" in e ? \"\" + e.booleanValue : \"integerValue\" in e ? \"\" + e.integerValue : \"doubleValue\" in e ? \"\" + e.doubleValue : \"timestampValue\" in e ? function __PRIVATE_canonifyTimestamp(e) {\n const t = __PRIVATE_normalizeTimestamp(e);\n return `time(${t.seconds},${t.nanos})`;\n }(e.timestampValue) : \"stringValue\" in e ? e.stringValue : \"bytesValue\" in e ? function __PRIVATE_canonifyByteString(e) {\n return __PRIVATE_normalizeByteString(e).toBase64();\n }(e.bytesValue) : \"referenceValue\" in e ? function __PRIVATE_canonifyReference(e) {\n return DocumentKey.fromName(e).toString();\n }(e.referenceValue) : \"geoPointValue\" in e ? function __PRIVATE_canonifyGeoPoint(e) {\n return `geo(${e.latitude},${e.longitude})`;\n }(e.geoPointValue) : \"arrayValue\" in e ? function __PRIVATE_canonifyArray(e) {\n let t = \"[\", n = !0;\n for (const r of e.values || []) n ? n = !1 : t += \",\", t += __PRIVATE_canonifyValue(r);\n return t + \"]\";\n }\n /**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */ (e.arrayValue) : \"mapValue\" in e ? function __PRIVATE_canonifyMap(e) {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const t = Object.keys(e.fields || {}).sort();\n let n = \"{\", r = !0;\n for (const i of t) r ? r = !1 : n += \",\", n += `${i}:${__PRIVATE_canonifyValue(e.fields[i])}`;\n return n + \"}\";\n }(e.mapValue) : fail();\n}\n\nfunction __PRIVATE_estimateByteSize(e) {\n switch (__PRIVATE_typeOrder(e)) {\n case 0 /* TypeOrder.NullValue */ :\n case 1 /* TypeOrder.BooleanValue */ :\n return 4;\n\n case 2 /* TypeOrder.NumberValue */ :\n return 8;\n\n case 3 /* TypeOrder.TimestampValue */ :\n case 8 /* TypeOrder.GeoPointValue */ :\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n const t = __PRIVATE_getPreviousValue(e);\n return t ? 16 + __PRIVATE_estimateByteSize(t) : 16;\n\n case 5 /* TypeOrder.StringValue */ :\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return 2 * e.stringValue.length;\n\n case 6 /* TypeOrder.BlobValue */ :\n return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize();\n\n case 7 /* TypeOrder.RefValue */ :\n return e.referenceValue.length;\n\n case 9 /* TypeOrder.ArrayValue */ :\n return function __PRIVATE_estimateArrayByteSize(e) {\n return (e.values || []).reduce(((e, t) => e + __PRIVATE_estimateByteSize(t)), 0);\n }\n /** Returns a reference value for the provided database and key. */ (e.arrayValue);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function __PRIVATE_estimateMapByteSize(e) {\n let t = 0;\n return forEach(e.fields, ((e, n) => {\n t += e.length + __PRIVATE_estimateByteSize(n);\n })), t;\n }(e.mapValue);\n\n default:\n throw fail();\n }\n}\n\nfunction __PRIVATE_refValue(e, t) {\n return {\n referenceValue: `projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */ function isInteger(e) {\n return !!e && \"integerValue\" in e;\n}\n\n/** Returns true if `value` is a DoubleValue. */\n/** Returns true if `value` is an ArrayValue. */\nfunction isArray(e) {\n return !!e && \"arrayValue\" in e;\n}\n\n/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(e) {\n return !!e && \"nullValue\" in e;\n}\n\n/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(e) {\n return !!e && \"doubleValue\" in e && isNaN(Number(e.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(e) {\n return !!e && \"mapValue\" in e;\n}\n\n/** Creates a deep copy of `source`. */ function __PRIVATE_deepClone(e) {\n if (e.geoPointValue) return {\n geoPointValue: Object.assign({}, e.geoPointValue)\n };\n if (e.timestampValue && \"object\" == typeof e.timestampValue) return {\n timestampValue: Object.assign({}, e.timestampValue)\n };\n if (e.mapValue) {\n const t = {\n mapValue: {\n fields: {}\n }\n };\n return forEach(e.mapValue.fields, ((e, n) => t.mapValue.fields[e] = __PRIVATE_deepClone(n))), \n t;\n }\n if (e.arrayValue) {\n const t = {\n arrayValue: {\n values: []\n }\n };\n for (let n = 0; n < (e.arrayValue.values || []).length; ++n) t.arrayValue.values[n] = __PRIVATE_deepClone(e.arrayValue.values[n]);\n return t;\n }\n return Object.assign({}, e);\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function __PRIVATE_isMaxValue(e) {\n return \"__max__\" === (((e.mapValue || {}).fields || {}).__type__ || {}).stringValue;\n}\n\n/** Returns the lowest value for the given value type (inclusive). */ function __PRIVATE_valuesGetLowerBound(e) {\n return \"nullValue\" in e ? ne : \"booleanValue\" in e ? {\n booleanValue: !1\n } : \"integerValue\" in e || \"doubleValue\" in e ? {\n doubleValue: NaN\n } : \"timestampValue\" in e ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"stringValue\" in e ? {\n stringValue: \"\"\n } : \"bytesValue\" in e ? {\n bytesValue: \"\"\n } : \"referenceValue\" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : \"geoPointValue\" in e ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"arrayValue\" in e ? {\n arrayValue: {}\n } : \"mapValue\" in e ? {\n mapValue: {}\n } : fail();\n}\n\n/** Returns the largest value for the given value type (exclusive). */ function __PRIVATE_valuesGetUpperBound(e) {\n return \"nullValue\" in e ? {\n booleanValue: !1\n } : \"booleanValue\" in e ? {\n doubleValue: NaN\n } : \"integerValue\" in e || \"doubleValue\" in e ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"timestampValue\" in e ? {\n stringValue: \"\"\n } : \"stringValue\" in e ? {\n bytesValue: \"\"\n } : \"bytesValue\" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : \"referenceValue\" in e ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"geoPointValue\" in e ? {\n arrayValue: {}\n } : \"arrayValue\" in e ? {\n mapValue: {}\n } : \"mapValue\" in e ? te : fail();\n}\n\nfunction __PRIVATE_lowerBoundCompare(e, t) {\n const n = __PRIVATE_valueCompare(e.value, t.value);\n return 0 !== n ? n : e.inclusive && !t.inclusive ? -1 : !e.inclusive && t.inclusive ? 1 : 0;\n}\n\nfunction __PRIVATE_upperBoundCompare(e, t) {\n const n = __PRIVATE_valueCompare(e.value, t.value);\n return 0 !== n ? n : e.inclusive && !t.inclusive ? 1 : !e.inclusive && t.inclusive ? -1 : 0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */ class ObjectValue {\n constructor(e) {\n this.value = e;\n }\n static empty() {\n return new ObjectValue({\n mapValue: {}\n });\n }\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */ field(e) {\n if (e.isEmpty()) return this.value;\n {\n let t = this.value;\n for (let n = 0; n < e.length - 1; ++n) if (t = (t.mapValue.fields || {})[e.get(n)], \n !__PRIVATE_isMapValue(t)) return null;\n return t = (t.mapValue.fields || {})[e.lastSegment()], t || null;\n }\n }\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */ set(e, t) {\n this.getFieldsMap(e.popLast())[e.lastSegment()] = __PRIVATE_deepClone(t);\n }\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */ setAll(e) {\n let t = FieldPath$1.emptyPath(), n = {}, r = [];\n e.forEach(((e, i) => {\n if (!t.isImmediateParentOf(i)) {\n // Insert the accumulated changes at this parent location\n const e = this.getFieldsMap(t);\n this.applyChanges(e, n, r), n = {}, r = [], t = i.popLast();\n }\n e ? n[i.lastSegment()] = __PRIVATE_deepClone(e) : r.push(i.lastSegment());\n }));\n const i = this.getFieldsMap(t);\n this.applyChanges(i, n, r);\n }\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */ delete(e) {\n const t = this.field(e.popLast());\n __PRIVATE_isMapValue(t) && t.mapValue.fields && delete t.mapValue.fields[e.lastSegment()];\n }\n isEqual(e) {\n return __PRIVATE_valueEquals(this.value, e.value);\n }\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */ getFieldsMap(e) {\n let t = this.value;\n t.mapValue.fields || (t.mapValue = {\n fields: {}\n });\n for (let n = 0; n < e.length; ++n) {\n let r = t.mapValue.fields[e.get(n)];\n __PRIVATE_isMapValue(r) && r.mapValue.fields || (r = {\n mapValue: {\n fields: {}\n }\n }, t.mapValue.fields[e.get(n)] = r), t = r;\n }\n return t.mapValue.fields;\n }\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */ applyChanges(e, t, n) {\n forEach(t, ((t, n) => e[t] = n));\n for (const t of n) delete e[t];\n }\n clone() {\n return new ObjectValue(__PRIVATE_deepClone(this.value));\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */ function __PRIVATE_extractFieldMask(e) {\n const t = [];\n return forEach(e.fields, ((e, n) => {\n const r = new FieldPath$1([ e ]);\n if (__PRIVATE_isMapValue(n)) {\n const e = __PRIVATE_extractFieldMask(n.mapValue).fields;\n if (0 === e.length) \n // Preserve the empty map by adding it to the FieldMask.\n t.push(r); else \n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const n of e) t.push(r.child(n));\n } else \n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n t.push(r);\n })), new FieldMask(t);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */ class MutableDocument {\n constructor(e, t, n, r, i, s, o) {\n this.key = e, this.documentType = t, this.version = n, this.readTime = r, this.createTime = i, \n this.data = s, this.documentState = o;\n }\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */ static newInvalidDocument(e) {\n return new MutableDocument(e, 0 /* DocumentType.INVALID */ , \n /* version */ SnapshotVersion.min(), \n /* readTime */ SnapshotVersion.min(), \n /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */ static newFoundDocument(e, t, n, r) {\n return new MutableDocument(e, 1 /* DocumentType.FOUND_DOCUMENT */ , \n /* version */ t, \n /* readTime */ SnapshotVersion.min(), \n /* createTime */ n, r, 0 /* DocumentState.SYNCED */);\n }\n /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(e, t) {\n return new MutableDocument(e, 2 /* DocumentType.NO_DOCUMENT */ , \n /* version */ t, \n /* readTime */ SnapshotVersion.min(), \n /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */ static newUnknownDocument(e, t) {\n return new MutableDocument(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n /* version */ t, \n /* readTime */ SnapshotVersion.min(), \n /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);\n }\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */ convertToFoundDocument(e, t) {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = e), \n this.version = e, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = t, \n this.documentState = 0 /* DocumentState.SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */ convertToNoDocument(e) {\n return this.version = e, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , \n this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , \n this;\n }\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */ convertToUnknownDocument(e) {\n return this.version = e, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , \n this;\n }\n setHasCommittedMutations() {\n return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;\n }\n setHasLocalMutations() {\n return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), \n this;\n }\n setReadTime(e) {\n return this.readTime = e, this;\n }\n get hasLocalMutations() {\n return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;\n }\n get hasCommittedMutations() {\n return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;\n }\n get hasPendingWrites() {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n isValidDocument() {\n return 0 /* DocumentType.INVALID */ !== this.documentType;\n }\n isFoundDocument() {\n return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;\n }\n isNoDocument() {\n return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;\n }\n isUnknownDocument() {\n return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;\n }\n isEqual(e) {\n return e instanceof MutableDocument && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data);\n }\n mutableCopy() {\n return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);\n }\n toString() {\n return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nclass Bound {\n constructor(e, t) {\n this.position = e, this.inclusive = t;\n }\n}\n\nfunction __PRIVATE_boundCompareToDocument(e, t, n) {\n let r = 0;\n for (let i = 0; i < e.position.length; i++) {\n const s = t[i], o = e.position[i];\n if (s.field.isKeyField()) r = DocumentKey.comparator(DocumentKey.fromName(o.referenceValue), n.key); else {\n r = __PRIVATE_valueCompare(o, n.data.field(s.field));\n }\n if (\"desc\" /* Direction.DESCENDING */ === s.dir && (r *= -1), 0 !== r) break;\n }\n return r;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */ function __PRIVATE_boundEquals(e, t) {\n if (null === e) return null === t;\n if (null === t) return !1;\n if (e.inclusive !== t.inclusive || e.position.length !== t.position.length) return !1;\n for (let n = 0; n < e.position.length; n++) {\n if (!__PRIVATE_valueEquals(e.position[n], t.position[n])) return !1;\n }\n return !0;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */ class OrderBy {\n constructor(e, t = \"asc\" /* Direction.ASCENDING */) {\n this.field = e, this.dir = t;\n }\n}\n\nfunction __PRIVATE_orderByEquals(e, t) {\n return e.dir === t.dir && e.field.isEqual(t.field);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Filter {}\n\nclass FieldFilter extends Filter {\n constructor(e, t, n) {\n super(), this.field = e, this.op = t, this.value = n;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(e, t, n) {\n return e.isKeyField() ? \"in\" /* Operator.IN */ === t || \"not-in\" /* Operator.NOT_IN */ === t ? this.createKeyFieldInFilter(e, t, n) : new __PRIVATE_KeyFieldFilter(e, t, n) : \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t ? new __PRIVATE_ArrayContainsFilter(e, n) : \"in\" /* Operator.IN */ === t ? new __PRIVATE_InFilter(e, n) : \"not-in\" /* Operator.NOT_IN */ === t ? new __PRIVATE_NotInFilter(e, n) : \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t ? new __PRIVATE_ArrayContainsAnyFilter(e, n) : new FieldFilter(e, t, n);\n }\n static createKeyFieldInFilter(e, t, n) {\n return \"in\" /* Operator.IN */ === t ? new __PRIVATE_KeyFieldInFilter(e, n) : new __PRIVATE_KeyFieldNotInFilter(e, n);\n }\n matches(e) {\n const t = e.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n return \"!=\" /* Operator.NOT_EQUAL */ === this.op ? null !== t && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)) : null !== t && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t) && this.matchesComparison(__PRIVATE_valueCompare(t, this.value));\n // Only compare types with matching backend order (such as double and int).\n }\n matchesComparison(e) {\n switch (this.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n return e < 0;\n\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n return e <= 0;\n\n case \"==\" /* Operator.EQUAL */ :\n return 0 === e;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return 0 !== e;\n\n case \">\" /* Operator.GREATER_THAN */ :\n return e > 0;\n\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n return e >= 0;\n\n default:\n return fail();\n }\n }\n isInequality() {\n return [ \"<\" /* Operator.LESS_THAN */ , \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ , \">\" /* Operator.GREATER_THAN */ , \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ , \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;\n }\n getFlattenedFilters() {\n return [ this ];\n }\n getFilters() {\n return [ this ];\n }\n}\n\nclass CompositeFilter extends Filter {\n constructor(e, t) {\n super(), this.filters = e, this.op = t, this.ue = null;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(e, t) {\n return new CompositeFilter(e, t);\n }\n matches(e) {\n return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t => !t.matches(e))) : void 0 !== this.filters.find((t => t.matches(e)));\n }\n getFlattenedFilters() {\n return null !== this.ue || (this.ue = this.filters.reduce(((e, t) => e.concat(t.getFlattenedFilters())), [])), \n this.ue;\n }\n // Returns a mutable copy of `this.filters`\n getFilters() {\n return Object.assign([], this.filters);\n }\n}\n\nfunction __PRIVATE_compositeFilterIsConjunction(e) {\n return \"and\" /* CompositeOperator.AND */ === e.op;\n}\n\nfunction __PRIVATE_compositeFilterIsDisjunction(e) {\n return \"or\" /* CompositeOperator.OR */ === e.op;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */ function __PRIVATE_compositeFilterIsFlatConjunction(e) {\n return __PRIVATE_compositeFilterIsFlat(e) && __PRIVATE_compositeFilterIsConjunction(e);\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */ function __PRIVATE_compositeFilterIsFlat(e) {\n for (const t of e.filters) if (t instanceof CompositeFilter) return !1;\n return !0;\n}\n\nfunction __PRIVATE_canonifyFilter(e) {\n if (e instanceof FieldFilter) \n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return e.field.canonicalString() + e.op.toString() + canonicalId(e.value);\n if (__PRIVATE_compositeFilterIsFlatConjunction(e)) \n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\");\n {\n // filter instanceof CompositeFilter\n const t = e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\");\n return `${e.op}(${t})`;\n }\n}\n\nfunction __PRIVATE_filterEquals(e, t) {\n return e instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(e, t) {\n return t instanceof FieldFilter && e.op === t.op && e.field.isEqual(t.field) && __PRIVATE_valueEquals(e.value, t.value);\n }(e, t) : e instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(e, t) {\n if (t instanceof CompositeFilter && e.op === t.op && e.filters.length === t.filters.length) {\n return e.filters.reduce(((e, n, r) => e && __PRIVATE_filterEquals(n, t.filters[r])), !0);\n }\n return !1;\n }\n /**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */ (e, t) : void fail();\n}\n\nfunction __PRIVATE_compositeFilterWithAddedFilters(e, t) {\n const n = e.filters.concat(t);\n return CompositeFilter.create(n, e.op);\n}\n\n/** Returns a debug description for `filter`. */ function __PRIVATE_stringifyFilter(e) {\n return e instanceof FieldFilter ? function __PRIVATE_stringifyFieldFilter(e) {\n return `${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`;\n }\n /** Filter that matches on key fields (i.e. '__name__'). */ (e) : e instanceof CompositeFilter ? function __PRIVATE_stringifyCompositeFilter(e) {\n return e.op.toString() + \" {\" + e.getFilters().map(__PRIVATE_stringifyFilter).join(\" ,\") + \"}\";\n }(e) : \"Filter\";\n}\n\nclass __PRIVATE_KeyFieldFilter extends FieldFilter {\n constructor(e, t, n) {\n super(e, t, n), this.key = DocumentKey.fromName(n.referenceValue);\n }\n matches(e) {\n const t = DocumentKey.comparator(e.key, this.key);\n return this.matchesComparison(t);\n }\n}\n\n/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"in\" /* Operator.IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue(\"in\" /* Operator.IN */ , t);\n }\n matches(e) {\n return this.keys.some((t => t.isEqual(e.key)));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"not-in\" /* Operator.NOT_IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue(\"not-in\" /* Operator.NOT_IN */ , t);\n }\n matches(e) {\n return !this.keys.some((t => t.isEqual(e.key)));\n }\n}\n\nfunction __PRIVATE_extractDocumentKeysFromArrayValue(e, t) {\n var n;\n return ((null === (n = t.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((e => DocumentKey.fromName(e.referenceValue)));\n}\n\n/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"array-contains\" /* Operator.ARRAY_CONTAINS */ , t);\n }\n matches(e) {\n const t = e.data.field(this.field);\n return isArray(t) && __PRIVATE_arrayValueContains(t.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"in\" /* Operator.IN */ , t);\n }\n matches(e) {\n const t = e.data.field(this.field);\n return null !== t && __PRIVATE_arrayValueContains(this.value.arrayValue, t);\n }\n}\n\n/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"not-in\" /* Operator.NOT_IN */ , t);\n }\n matches(e) {\n if (__PRIVATE_arrayValueContains(this.value.arrayValue, {\n nullValue: \"NULL_VALUE\"\n })) return !1;\n const t = e.data.field(this.field);\n return null !== t && !__PRIVATE_arrayValueContains(this.value.arrayValue, t);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter {\n constructor(e, t) {\n super(e, \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , t);\n }\n matches(e) {\n const t = e.data.field(this.field);\n return !(!isArray(t) || !t.arrayValue.values) && t.arrayValue.values.some((e => __PRIVATE_arrayValueContains(this.value.arrayValue, e)));\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Visible for testing\nclass __PRIVATE_TargetImpl {\n constructor(e, t = null, n = [], r = [], i = null, s = null, o = null) {\n this.path = e, this.collectionGroup = t, this.orderBy = n, this.filters = r, this.limit = i, \n this.startAt = s, this.endAt = o, this.ce = null;\n }\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */ function __PRIVATE_newTarget(e, t = null, n = [], r = [], i = null, s = null, o = null) {\n return new __PRIVATE_TargetImpl(e, t, n, r, i, s, o);\n}\n\nfunction __PRIVATE_canonifyTarget(e) {\n const t = __PRIVATE_debugCast(e);\n if (null === t.ce) {\n let e = t.path.canonicalString();\n null !== t.collectionGroup && (e += \"|cg:\" + t.collectionGroup), e += \"|f:\", e += t.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\"), \n e += \"|ob:\", e += t.orderBy.map((e => function __PRIVATE_canonifyOrderBy(e) {\n // TODO(b/29183165): Make this collision robust.\n return e.field.canonicalString() + e.dir;\n }(e))).join(\",\"), __PRIVATE_isNullOrUndefined(t.limit) || (e += \"|l:\", e += t.limit), \n t.startAt && (e += \"|lb:\", e += t.startAt.inclusive ? \"b:\" : \"a:\", e += t.startAt.position.map((e => canonicalId(e))).join(\",\")), \n t.endAt && (e += \"|ub:\", e += t.endAt.inclusive ? \"a:\" : \"b:\", e += t.endAt.position.map((e => canonicalId(e))).join(\",\")), \n t.ce = e;\n }\n return t.ce;\n}\n\nfunction __PRIVATE_targetEquals(e, t) {\n if (e.limit !== t.limit) return !1;\n if (e.orderBy.length !== t.orderBy.length) return !1;\n for (let n = 0; n < e.orderBy.length; n++) if (!__PRIVATE_orderByEquals(e.orderBy[n], t.orderBy[n])) return !1;\n if (e.filters.length !== t.filters.length) return !1;\n for (let n = 0; n < e.filters.length; n++) if (!__PRIVATE_filterEquals(e.filters[n], t.filters[n])) return !1;\n return e.collectionGroup === t.collectionGroup && (!!e.path.isEqual(t.path) && (!!__PRIVATE_boundEquals(e.startAt, t.startAt) && __PRIVATE_boundEquals(e.endAt, t.endAt)));\n}\n\nfunction __PRIVATE_targetIsDocumentTarget(e) {\n return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;\n}\n\n/** Returns the field filters that target the given field path. */ function __PRIVATE_targetGetFieldFiltersForPath(e, t) {\n return e.filters.filter((e => e instanceof FieldFilter && e.field.isEqual(t)));\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction __PRIVATE_targetGetAscendingBound(e, t, n) {\n let r = ne, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {\n let e = ne, t = !0;\n switch (n.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n e = __PRIVATE_valuesGetLowerBound(n.value);\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n e = n.value;\n break;\n\n case \">\" /* Operator.GREATER_THAN */ :\n e = n.value, t = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n e = ne;\n // Remaining filters cannot be used as lower bounds.\n }\n __PRIVATE_lowerBoundCompare({\n value: r,\n inclusive: i\n }, {\n value: e,\n inclusive: t\n }) < 0 && (r = e, i = t);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {\n if (e.orderBy[s].field.isEqual(t)) {\n const e = n.position[s];\n __PRIVATE_lowerBoundCompare({\n value: r,\n inclusive: i\n }, {\n value: e,\n inclusive: n.inclusive\n }) < 0 && (r = e, i = n.inclusive);\n break;\n }\n }\n return {\n value: r,\n inclusive: i\n };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */ function __PRIVATE_targetGetDescendingBound(e, t, n) {\n let r = te, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {\n let e = te, t = !0;\n switch (n.op) {\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n case \">\" /* Operator.GREATER_THAN */ :\n e = __PRIVATE_valuesGetUpperBound(n.value), t = !1;\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n e = n.value;\n break;\n\n case \"<\" /* Operator.LESS_THAN */ :\n e = n.value, t = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n e = te;\n // Remaining filters cannot be used as upper bounds.\n }\n __PRIVATE_upperBoundCompare({\n value: r,\n inclusive: i\n }, {\n value: e,\n inclusive: t\n }) > 0 && (r = e, i = t);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {\n if (e.orderBy[s].field.isEqual(t)) {\n const e = n.position[s];\n __PRIVATE_upperBoundCompare({\n value: r,\n inclusive: i\n }, {\n value: e,\n inclusive: n.inclusive\n }) > 0 && (r = e, i = n.inclusive);\n break;\n }\n }\n return {\n value: r,\n inclusive: i\n };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nclass __PRIVATE_QueryImpl {\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(e, t = null, n = [], r = [], i = null, s = \"F\" /* LimitType.First */ , o = null, _ = null) {\n this.path = e, this.collectionGroup = t, this.explicitOrderBy = n, this.filters = r, \n this.limit = i, this.limitType = s, this.startAt = o, this.endAt = _, this.le = null, \n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n this.he = null, \n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n this.Pe = null, this.startAt, this.endAt;\n }\n}\n\n/** Creates a new Query instance with the options provided. */ function __PRIVATE_newQuery(e, t, n, r, i, s, o, _) {\n return new __PRIVATE_QueryImpl(e, t, n, r, i, s, o, _);\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */ function __PRIVATE_newQueryForPath(e) {\n return new __PRIVATE_QueryImpl(e);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nfunction __PRIVATE_queryMatchesAllDocuments(e) {\n return 0 === e.filters.length && null === e.limit && null == e.startAt && null == e.endAt && (0 === e.explicitOrderBy.length || 1 === e.explicitOrderBy.length && e.explicitOrderBy[0].field.isKeyField());\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nfunction __PRIVATE_isCollectionGroupQuery(e) {\n return null !== e.collectionGroup;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */ function __PRIVATE_queryNormalizedOrderBy(e) {\n const t = __PRIVATE_debugCast(e);\n if (null === t.le) {\n t.le = [];\n const e = new Set;\n // Any explicit order by fields should be added as is.\n for (const n of t.explicitOrderBy) t.le.push(n), e.add(n.field.canonicalString());\n // The order of the implicit ordering always matches the last explicit order by.\n const n = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : \"asc\" /* Direction.ASCENDING */ , r = function __PRIVATE_getInequalityFilterFields(e) {\n let t = new SortedSet(FieldPath$1.comparator);\n return e.filters.forEach((e => {\n e.getFlattenedFilters().forEach((e => {\n e.isInequality() && (t = t.add(e.field));\n }));\n })), t;\n }\n /**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */ (t);\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n r.forEach((r => {\n e.has(r.canonicalString()) || r.isKeyField() || t.le.push(new OrderBy(r, n));\n })), \n // Add the document key field to the last if it is not explicitly ordered.\n e.has(FieldPath$1.keyField().canonicalString()) || t.le.push(new OrderBy(FieldPath$1.keyField(), n));\n }\n return t.le;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */ function __PRIVATE_queryToTarget(e) {\n const t = __PRIVATE_debugCast(e);\n return t.he || (t.he = __PRIVATE__queryToTarget(t, __PRIVATE_queryNormalizedOrderBy(e))), \n t.he;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */ function __PRIVATE__queryToTarget(e, t) {\n if (\"F\" /* LimitType.First */ === e.limitType) return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, e.startAt, e.endAt);\n {\n // Flip the orderBy directions since we want the last results\n t = t.map((e => {\n const t = \"desc\" /* Direction.DESCENDING */ === e.dir ? \"asc\" /* Direction.ASCENDING */ : \"desc\" /* Direction.DESCENDING */;\n return new OrderBy(e.field, t);\n }));\n // We need to swap the cursors to match the now-flipped query ordering.\n const n = e.endAt ? new Bound(e.endAt.position, e.endAt.inclusive) : null, r = e.startAt ? new Bound(e.startAt.position, e.startAt.inclusive) : null;\n // Now return as a LimitType.First query.\n return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, n, r);\n }\n}\n\nfunction __PRIVATE_queryWithAddedFilter(e, t) {\n const n = e.filters.concat([ t ]);\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), n, e.limit, e.limitType, e.startAt, e.endAt);\n}\n\nfunction __PRIVATE_queryWithLimit(e, t, n) {\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), t, n, e.startAt, e.endAt);\n}\n\nfunction __PRIVATE_queryEquals(e, t) {\n return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e), __PRIVATE_queryToTarget(t)) && e.limitType === t.limitType;\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nfunction __PRIVATE_canonifyQuery(e) {\n return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`;\n}\n\nfunction __PRIVATE_stringifyQuery(e) {\n return `Query(target=${function __PRIVATE_stringifyTarget(e) {\n let t = e.path.canonicalString();\n return null !== e.collectionGroup && (t += \" collectionGroup=\" + e.collectionGroup), \n e.filters.length > 0 && (t += `, filters: [${e.filters.map((e => __PRIVATE_stringifyFilter(e))).join(\", \")}]`), \n __PRIVATE_isNullOrUndefined(e.limit) || (t += \", limit: \" + e.limit), e.orderBy.length > 0 && (t += `, orderBy: [${e.orderBy.map((e => function __PRIVATE_stringifyOrderBy(e) {\n return `${e.field.canonicalString()} (${e.dir})`;\n }(e))).join(\", \")}]`), e.startAt && (t += \", startAt: \", t += e.startAt.inclusive ? \"b:\" : \"a:\", \n t += e.startAt.position.map((e => canonicalId(e))).join(\",\")), e.endAt && (t += \", endAt: \", \n t += e.endAt.inclusive ? \"a:\" : \"b:\", t += e.endAt.position.map((e => canonicalId(e))).join(\",\")), \n `Target(${t})`;\n }(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */ function __PRIVATE_queryMatches(e, t) {\n return t.isFoundDocument() && function __PRIVATE_queryMatchesPathAndCollectionGroup(e, t) {\n const n = t.key.path;\n return null !== e.collectionGroup ? t.key.hasCollectionId(e.collectionGroup) && e.path.isPrefixOf(n) : DocumentKey.isDocumentKey(e.path) ? e.path.isEqual(n) : e.path.isImmediateParentOf(n);\n }\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */ (e, t) && function __PRIVATE_queryMatchesOrderBy(e, t) {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const n of __PRIVATE_queryNormalizedOrderBy(e)) \n // order-by key always matches\n if (!n.field.isKeyField() && null === t.data.field(n.field)) return !1;\n return !0;\n }(e, t) && function __PRIVATE_queryMatchesFilters(e, t) {\n for (const n of e.filters) if (!n.matches(t)) return !1;\n return !0;\n }\n /** Makes sure a document is within the bounds, if provided. */ (e, t) && function __PRIVATE_queryMatchesBounds(e, t) {\n if (e.startAt && !\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n function __PRIVATE_boundSortsBeforeDocument(e, t, n) {\n const r = __PRIVATE_boundCompareToDocument(e, t, n);\n return e.inclusive ? r <= 0 : r < 0;\n }(e.startAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1;\n if (e.endAt && !function __PRIVATE_boundSortsAfterDocument(e, t, n) {\n const r = __PRIVATE_boundCompareToDocument(e, t, n);\n return e.inclusive ? r >= 0 : r > 0;\n }(e.endAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1;\n return !0;\n }\n /**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */ (e, t);\n}\n\nfunction __PRIVATE_queryCollectionGroup(e) {\n return e.collectionGroup || (e.path.length % 2 == 1 ? e.path.lastSegment() : e.path.get(e.path.length - 2));\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */ function __PRIVATE_newQueryComparator(e) {\n return (t, n) => {\n let r = !1;\n for (const i of __PRIVATE_queryNormalizedOrderBy(e)) {\n const e = __PRIVATE_compareDocs(i, t, n);\n if (0 !== e) return e;\n r = r || i.field.isKeyField();\n }\n return 0;\n };\n}\n\nfunction __PRIVATE_compareDocs(e, t, n) {\n const r = e.field.isKeyField() ? DocumentKey.comparator(t.key, n.key) : function __PRIVATE_compareDocumentsByField(e, t, n) {\n const r = t.data.field(e), i = n.data.field(e);\n return null !== r && null !== i ? __PRIVATE_valueCompare(r, i) : fail();\n }(e.field, t, n);\n switch (e.dir) {\n case \"asc\" /* Direction.ASCENDING */ :\n return r;\n\n case \"desc\" /* Direction.DESCENDING */ :\n return -1 * r;\n\n default:\n return fail();\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */ class ObjectMap {\n constructor(e, t) {\n this.mapKeyFn = e, this.equalsFn = t, \n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n this.inner = {}, \n /** The number of entries stored in the map */\n this.innerSize = 0;\n }\n /** Get a value for this key, or undefined if it does not exist. */ get(e) {\n const t = this.mapKeyFn(e), n = this.inner[t];\n if (void 0 !== n) for (const [t, r] of n) if (this.equalsFn(t, e)) return r;\n }\n has(e) {\n return void 0 !== this.get(e);\n }\n /** Put this key and value in the map. */ set(e, t) {\n const n = this.mapKeyFn(e), r = this.inner[n];\n if (void 0 === r) return this.inner[n] = [ [ e, t ] ], void this.innerSize++;\n for (let n = 0; n < r.length; n++) if (this.equalsFn(r[n][0], e)) \n // This is updating an existing entry and does not increase `innerSize`.\n return void (r[n] = [ e, t ]);\n r.push([ e, t ]), this.innerSize++;\n }\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */ delete(e) {\n const t = this.mapKeyFn(e), n = this.inner[t];\n if (void 0 === n) return !1;\n for (let r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], e)) return 1 === n.length ? delete this.inner[t] : n.splice(r, 1), \n this.innerSize--, !0;\n return !1;\n }\n forEach(e) {\n forEach(this.inner, ((t, n) => {\n for (const [t, r] of n) e(t, r);\n }));\n }\n isEmpty() {\n return isEmpty(this.inner);\n }\n size() {\n return this.innerSize;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const re = new SortedMap(DocumentKey.comparator);\n\nfunction __PRIVATE_mutableDocumentMap() {\n return re;\n}\n\nconst ie = new SortedMap(DocumentKey.comparator);\n\nfunction documentMap(...e) {\n let t = ie;\n for (const n of e) t = t.insert(n.key, n);\n return t;\n}\n\nfunction __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) {\n let t = ie;\n return e.forEach(((e, n) => t = t.insert(e, n.overlayedDocument))), t;\n}\n\nfunction __PRIVATE_newOverlayMap() {\n return __PRIVATE_newDocumentKeyMap();\n}\n\nfunction __PRIVATE_newMutationMap() {\n return __PRIVATE_newDocumentKeyMap();\n}\n\nfunction __PRIVATE_newDocumentKeyMap() {\n return new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t)));\n}\n\nconst se = new SortedMap(DocumentKey.comparator);\n\nconst oe = new SortedSet(DocumentKey.comparator);\n\nfunction __PRIVATE_documentKeySet(...e) {\n let t = oe;\n for (const n of e) t = t.add(n);\n return t;\n}\n\nconst _e = new SortedSet(__PRIVATE_primitiveComparator);\n\nfunction __PRIVATE_targetIdSet() {\n return _e;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */ function __PRIVATE_toDouble(e, t) {\n if (e.useProto3Json) {\n if (isNaN(t)) return {\n doubleValue: \"NaN\"\n };\n if (t === 1 / 0) return {\n doubleValue: \"Infinity\"\n };\n if (t === -1 / 0) return {\n doubleValue: \"-Infinity\"\n };\n }\n return {\n doubleValue: __PRIVATE_isNegativeZero(t) ? \"-0\" : t\n };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */ function __PRIVATE_toInteger(e) {\n return {\n integerValue: \"\" + e\n };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */ function toNumber(e, t) {\n return isSafeInteger(t) ? __PRIVATE_toInteger(t) : __PRIVATE_toDouble(e, t);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Used to represent a field transform on a mutation. */ class TransformOperation {\n constructor() {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n this._ = void 0;\n }\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */ function __PRIVATE_applyTransformOperationToLocalView(e, t, n) {\n return e instanceof __PRIVATE_ServerTimestampTransform ? function serverTimestamp$1(e, t) {\n const n = {\n fields: {\n __type__: {\n stringValue: \"server_timestamp\"\n },\n __local_write_time__: {\n timestampValue: {\n seconds: e.seconds,\n nanos: e.nanoseconds\n }\n }\n }\n };\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n return t && __PRIVATE_isServerTimestamp(t) && (t = __PRIVATE_getPreviousValue(t)), \n t && (n.fields.__previous_value__ = t), {\n mapValue: n\n };\n }(n, t) : e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e, t) {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const n = __PRIVATE_computeTransformOperationBaseValue(e, t), r = asNumber(n) + asNumber(e.Ie);\n return isInteger(n) && isInteger(e.Ie) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e.serializer, r);\n }(e, t);\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */ function __PRIVATE_applyTransformOperationToRemoteDocument(e, t, n) {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n return e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : n;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */ function __PRIVATE_computeTransformOperationBaseValue(e, t) {\n return e instanceof __PRIVATE_NumericIncrementTransformOperation ? \n /** Returns true if `value` is either an IntegerValue or a DoubleValue. */\n function __PRIVATE_isNumber(e) {\n return isInteger(e) || function __PRIVATE_isDouble(e) {\n return !!e && \"doubleValue\" in e;\n }(e);\n }(t) ? t : {\n integerValue: 0\n } : null;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nclass __PRIVATE_ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation {\n constructor(e) {\n super(), this.elements = e;\n }\n}\n\nfunction __PRIVATE_applyArrayUnionTransformOperation(e, t) {\n const n = __PRIVATE_coercedFieldValuesArray(t);\n for (const t of e.elements) n.some((e => __PRIVATE_valueEquals(e, t))) || n.push(t);\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation {\n constructor(e) {\n super(), this.elements = e;\n }\n}\n\nfunction __PRIVATE_applyArrayRemoveTransformOperation(e, t) {\n let n = __PRIVATE_coercedFieldValuesArray(t);\n for (const t of e.elements) n = n.filter((e => !__PRIVATE_valueEquals(e, t)));\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation {\n constructor(e, t) {\n super(), this.serializer = e, this.Ie = t;\n }\n}\n\nfunction asNumber(e) {\n return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);\n}\n\nfunction __PRIVATE_coercedFieldValuesArray(e) {\n return isArray(e) && e.arrayValue.values ? e.arrayValue.values.slice() : [];\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A field path and the TransformOperation to perform upon it. */ class FieldTransform {\n constructor(e, t) {\n this.field = e, this.transform = t;\n }\n}\n\nfunction __PRIVATE_fieldTransformEquals(e, t) {\n return e.field.isEqual(t.field) && function __PRIVATE_transformOperationEquals(e, t) {\n return e instanceof __PRIVATE_ArrayUnionTransformOperation && t instanceof __PRIVATE_ArrayUnionTransformOperation || e instanceof __PRIVATE_ArrayRemoveTransformOperation && t instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_arrayEquals(e.elements, t.elements, __PRIVATE_valueEquals) : e instanceof __PRIVATE_NumericIncrementTransformOperation && t instanceof __PRIVATE_NumericIncrementTransformOperation ? __PRIVATE_valueEquals(e.Ie, t.Ie) : e instanceof __PRIVATE_ServerTimestampTransform && t instanceof __PRIVATE_ServerTimestampTransform;\n }(e.transform, t.transform);\n}\n\n/** The result of successfully applying a mutation to the backend. */\nclass MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n e, \n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n t) {\n this.version = e, this.transformResults = t;\n }\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */ class Precondition {\n constructor(e, t) {\n this.updateTime = e, this.exists = t;\n }\n /** Creates a new empty Precondition. */ static none() {\n return new Precondition;\n }\n /** Creates a new Precondition with an exists flag. */ static exists(e) {\n return new Precondition(void 0, e);\n }\n /** Creates a new Precondition based on a version a document exists at. */ static updateTime(e) {\n return new Precondition(e);\n }\n /** Returns whether this Precondition is empty. */ get isNone() {\n return void 0 === this.updateTime && void 0 === this.exists;\n }\n isEqual(e) {\n return this.exists === e.exists && (this.updateTime ? !!e.updateTime && this.updateTime.isEqual(e.updateTime) : !e.updateTime);\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */ function __PRIVATE_preconditionIsValidForDocument(e, t) {\n return void 0 !== e.updateTime ? t.isFoundDocument() && t.version.isEqual(e.updateTime) : void 0 === e.exists || e.exists === t.isFoundDocument();\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */ class Mutation {}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */ function __PRIVATE_calculateOverlayMutation(e, t) {\n if (!e.hasLocalMutations || t && 0 === t.fields.length) return null;\n // mask is null when sets or deletes are applied to the current document.\n if (null === t) return e.isNoDocument() ? new __PRIVATE_DeleteMutation(e.key, Precondition.none()) : new __PRIVATE_SetMutation(e.key, e.data, Precondition.none());\n {\n const n = e.data, r = ObjectValue.empty();\n let i = new SortedSet(FieldPath$1.comparator);\n for (let e of t.fields) if (!i.has(e)) {\n let t = n.field(e);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n null === t && e.length > 1 && (e = e.popLast(), t = n.field(e)), null === t ? r.delete(e) : r.set(e, t), \n i = i.add(e);\n }\n return new __PRIVATE_PatchMutation(e.key, r, new FieldMask(i.toArray()), Precondition.none());\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */ function __PRIVATE_mutationApplyToRemoteDocument(e, t, n) {\n e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToRemoteDocument(e, t, n) {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const r = e.value.clone(), i = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults);\n r.setAll(i), t.convertToFoundDocument(n.version, r).setHasCommittedMutations();\n }(e, t, n) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToRemoteDocument(e, t, n) {\n if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) \n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n return void t.convertToUnknownDocument(n.version);\n const r = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults), i = t.data;\n i.setAll(__PRIVATE_getPatch(e)), i.setAll(r), t.convertToFoundDocument(n.version, i).setHasCommittedMutations();\n }(e, t, n) : function __PRIVATE_deleteMutationApplyToRemoteDocument(e, t, n) {\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n t.convertToNoDocument(n.version).setHasCommittedMutations();\n }(0, t, n);\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */ function __PRIVATE_mutationApplyToLocalView(e, t, n, r) {\n return e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToLocalView(e, t, n, r) {\n if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) \n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return n;\n const i = e.value.clone(), s = __PRIVATE_localTransformResults(e.fieldTransforms, r, t);\n return i.setAll(s), t.convertToFoundDocument(t.version, i).setHasLocalMutations(), \n null;\n // SetMutation overwrites all fields.\n }\n /**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */ (e, t, n, r) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToLocalView(e, t, n, r) {\n if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return n;\n const i = __PRIVATE_localTransformResults(e.fieldTransforms, r, t), s = t.data;\n if (s.setAll(__PRIVATE_getPatch(e)), s.setAll(i), t.convertToFoundDocument(t.version, s).setHasLocalMutations(), \n null === n) return null;\n return n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e => e.field)));\n }\n /**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */ (e, t, n, r) : function __PRIVATE_deleteMutationApplyToLocalView(e, t, n) {\n if (__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return t.convertToNoDocument(t.version).setHasLocalMutations(), \n null;\n return n;\n }\n /**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */ (e, t, n);\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */ function __PRIVATE_mutationExtractBaseValue(e, t) {\n let n = null;\n for (const r of e.fieldTransforms) {\n const e = t.data.field(r.field), i = __PRIVATE_computeTransformOperationBaseValue(r.transform, e || null);\n null != i && (null === n && (n = ObjectValue.empty()), n.set(r.field, i));\n }\n return n || null;\n}\n\nfunction __PRIVATE_mutationEquals(e, t) {\n return e.type === t.type && (!!e.key.isEqual(t.key) && (!!e.precondition.isEqual(t.precondition) && (!!function __PRIVATE_fieldTransformsAreEqual(e, t) {\n return void 0 === e && void 0 === t || !(!e || !t) && __PRIVATE_arrayEquals(e, t, ((e, t) => __PRIVATE_fieldTransformEquals(e, t)));\n }(e.fieldTransforms, t.fieldTransforms) && (0 /* MutationType.Set */ === e.type ? e.value.isEqual(t.value) : 1 /* MutationType.Patch */ !== e.type || e.data.isEqual(t.data) && e.fieldMask.isEqual(t.fieldMask)))));\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */ class __PRIVATE_SetMutation extends Mutation {\n constructor(e, t, n, r = []) {\n super(), this.key = e, this.value = t, this.precondition = n, this.fieldTransforms = r, \n this.type = 0 /* MutationType.Set */;\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass __PRIVATE_PatchMutation extends Mutation {\n constructor(e, t, n, r, i = []) {\n super(), this.key = e, this.data = t, this.fieldMask = n, this.precondition = r, \n this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;\n }\n getFieldMask() {\n return this.fieldMask;\n }\n}\n\nfunction __PRIVATE_getPatch(e) {\n const t = new Map;\n return e.fieldMask.fields.forEach((n => {\n if (!n.isEmpty()) {\n const r = e.data.field(n);\n t.set(n, r);\n }\n })), t;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */ function __PRIVATE_serverTransformResults(e, t, n) {\n const r = new Map;\n __PRIVATE_hardAssert(e.length === n.length);\n for (let i = 0; i < n.length; i++) {\n const s = e[i], o = s.transform, _ = t.data.field(s.field);\n r.set(s.field, __PRIVATE_applyTransformOperationToRemoteDocument(o, _, n[i]));\n }\n return r;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */ function __PRIVATE_localTransformResults(e, t, n) {\n const r = new Map;\n for (const i of e) {\n const e = i.transform, s = n.data.field(i.field);\n r.set(i.field, __PRIVATE_applyTransformOperationToLocalView(e, s, t));\n }\n return r;\n}\n\n/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation {\n constructor(e, t) {\n super(), this.key = e, this.precondition = t, this.type = 2 /* MutationType.Delete */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass __PRIVATE_VerifyMutation extends Mutation {\n constructor(e, t) {\n super(), this.key = e, this.precondition = t, this.type = 3 /* MutationType.Verify */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */ class MutationBatch {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(e, t, n, r) {\n this.batchId = e, this.localWriteTime = t, this.baseMutations = n, this.mutations = r;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */ applyToRemoteDocument(e, t) {\n const n = t.mutationResults;\n for (let t = 0; t < this.mutations.length; t++) {\n const r = this.mutations[t];\n if (r.key.isEqual(e.key)) {\n __PRIVATE_mutationApplyToRemoteDocument(r, e, n[t]);\n }\n }\n }\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */ applyToLocalView(e, t) {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const n of this.baseMutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));\n // Second, apply all user-provided mutations.\n for (const n of this.mutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));\n return t;\n }\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */ applyToLocalDocumentSet(e, t) {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const n = __PRIVATE_newMutationMap();\n return this.mutations.forEach((r => {\n const i = e.get(r.key), s = i.overlayedDocument;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n let o = this.applyToLocalView(s, i.mutatedFields);\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n o = t.has(r.key) ? null : o;\n const _ = __PRIVATE_calculateOverlayMutation(s, o);\n null !== _ && n.set(r.key, _), s.isValidDocument() || s.convertToNoDocument(SnapshotVersion.min());\n })), n;\n }\n keys() {\n return this.mutations.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet());\n }\n isEqual(e) {\n return this.batchId === e.batchId && __PRIVATE_arrayEquals(this.mutations, e.mutations, ((e, t) => __PRIVATE_mutationEquals(e, t))) && __PRIVATE_arrayEquals(this.baseMutations, e.baseMutations, ((e, t) => __PRIVATE_mutationEquals(e, t)));\n }\n}\n\n/** The result of applying a mutation batch to the backend. */ class MutationBatchResult {\n constructor(e, t, n, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n r) {\n this.batch = e, this.commitVersion = t, this.mutationResults = n, this.docVersions = r;\n }\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */ static from(e, t, n) {\n __PRIVATE_hardAssert(e.mutations.length === n.length);\n let r = function __PRIVATE_documentVersionMap() {\n return se;\n }();\n const i = e.mutations;\n for (let e = 0; e < i.length; e++) r = r.insert(i[e].key, n[e].version);\n return new MutationBatchResult(e, t, n, r);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */ class Overlay {\n constructor(e, t) {\n this.largestBatchId = e, this.mutation = t;\n }\n getKey() {\n return this.mutation.key;\n }\n isEqual(e) {\n return null !== e && this.mutation === e.mutation;\n }\n toString() {\n return `Overlay{\\n largestBatchId: ${this.largestBatchId},\\n mutation: ${this.mutation.toString()}\\n }`;\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Concrete implementation of the Aggregate type.\n */ class __PRIVATE_AggregateImpl {\n constructor(e, t, n) {\n this.alias = e, this.aggregateType = t, this.fieldPath = n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class ExistenceFilter {\n constructor(e, t) {\n this.count = e, this.unchangedNames = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */ var ae, ue;\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nfunction __PRIVATE_isPermanentError(e) {\n switch (e) {\n default:\n return fail();\n\n case D.CANCELLED:\n case D.UNKNOWN:\n case D.DEADLINE_EXCEEDED:\n case D.RESOURCE_EXHAUSTED:\n case D.INTERNAL:\n case D.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case D.UNAUTHENTICATED:\n return !1;\n\n case D.INVALID_ARGUMENT:\n case D.NOT_FOUND:\n case D.ALREADY_EXISTS:\n case D.PERMISSION_DENIED:\n case D.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case D.ABORTED:\n case D.OUT_OF_RANGE:\n case D.UNIMPLEMENTED:\n case D.DATA_LOSS:\n return !0;\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nfunction __PRIVATE_mapCodeFromRpcCode(e) {\n if (void 0 === e) \n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n return __PRIVATE_logError(\"GRPC error has no .code\"), D.UNKNOWN;\n switch (e) {\n case ae.OK:\n return D.OK;\n\n case ae.CANCELLED:\n return D.CANCELLED;\n\n case ae.UNKNOWN:\n return D.UNKNOWN;\n\n case ae.DEADLINE_EXCEEDED:\n return D.DEADLINE_EXCEEDED;\n\n case ae.RESOURCE_EXHAUSTED:\n return D.RESOURCE_EXHAUSTED;\n\n case ae.INTERNAL:\n return D.INTERNAL;\n\n case ae.UNAVAILABLE:\n return D.UNAVAILABLE;\n\n case ae.UNAUTHENTICATED:\n return D.UNAUTHENTICATED;\n\n case ae.INVALID_ARGUMENT:\n return D.INVALID_ARGUMENT;\n\n case ae.NOT_FOUND:\n return D.NOT_FOUND;\n\n case ae.ALREADY_EXISTS:\n return D.ALREADY_EXISTS;\n\n case ae.PERMISSION_DENIED:\n return D.PERMISSION_DENIED;\n\n case ae.FAILED_PRECONDITION:\n return D.FAILED_PRECONDITION;\n\n case ae.ABORTED:\n return D.ABORTED;\n\n case ae.OUT_OF_RANGE:\n return D.OUT_OF_RANGE;\n\n case ae.UNIMPLEMENTED:\n return D.UNIMPLEMENTED;\n\n case ae.DATA_LOSS:\n return D.DATA_LOSS;\n\n default:\n return fail();\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */ (ue = ae || (ae = {}))[ue.OK = 0] = \"OK\", ue[ue.CANCELLED = 1] = \"CANCELLED\", \nue[ue.UNKNOWN = 2] = \"UNKNOWN\", ue[ue.INVALID_ARGUMENT = 3] = \"INVALID_ARGUMENT\", \nue[ue.DEADLINE_EXCEEDED = 4] = \"DEADLINE_EXCEEDED\", ue[ue.NOT_FOUND = 5] = \"NOT_FOUND\", \nue[ue.ALREADY_EXISTS = 6] = \"ALREADY_EXISTS\", ue[ue.PERMISSION_DENIED = 7] = \"PERMISSION_DENIED\", \nue[ue.UNAUTHENTICATED = 16] = \"UNAUTHENTICATED\", ue[ue.RESOURCE_EXHAUSTED = 8] = \"RESOURCE_EXHAUSTED\", \nue[ue.FAILED_PRECONDITION = 9] = \"FAILED_PRECONDITION\", ue[ue.ABORTED = 10] = \"ABORTED\", \nue[ue.OUT_OF_RANGE = 11] = \"OUT_OF_RANGE\", ue[ue.UNIMPLEMENTED = 12] = \"UNIMPLEMENTED\", \nue[ue.INTERNAL = 13] = \"INTERNAL\", ue[ue.UNAVAILABLE = 14] = \"UNAVAILABLE\", ue[ue.DATA_LOSS = 15] = \"DATA_LOSS\";\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The global, singleton instance of TestingHooksSpi.\n *\n * This variable will be `null` in all cases _except_ when running from\n * integration tests that have registered callbacks to be notified of events\n * that happen during the test execution.\n */\nlet ce = null;\n\n/**\n * Sets the value of the `testingHooksSpi` object.\n * @param instance the instance to set.\n */\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\nfunction __PRIVATE_newTextEncoder() {\n return new TextEncoder;\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst le = new _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Integer([ 4294967295, 4294967295 ], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction __PRIVATE_getMd5HashValue(e) {\n const t = __PRIVATE_newTextEncoder().encode(e), n = new _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Md5;\n return n.update(t), new Uint8Array(n.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2’s complement using little endian.\nfunction __PRIVATE_get64BitUints(e) {\n const t = new DataView(e.buffer), n = t.getUint32(0, /* littleEndian= */ !0), r = t.getUint32(4, /* littleEndian= */ !0), i = t.getUint32(8, /* littleEndian= */ !0), s = t.getUint32(12, /* littleEndian= */ !0);\n return [ new _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Integer([ n, r ], 0), new _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Integer([ i, s ], 0) ];\n}\n\nclass BloomFilter {\n constructor(e, t, n) {\n if (this.bitmap = e, this.padding = t, this.hashCount = n, t < 0 || t >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t}`);\n if (n < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);\n if (e.length > 0 && 0 === this.hashCount) \n // Only empty bloom filter can have 0 hash count.\n throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);\n if (0 === e.length && 0 !== t) \n // Empty bloom filter should have 0 padding.\n throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t}`);\n this.Te = 8 * e.length - t, \n // Set the bit count in Integer to avoid repetition in mightContain().\n this.Ee = _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Integer.fromNumber(this.Te);\n }\n // Calculate the ith hash value based on the hashed 64bit integers,\n // and calculate its corresponding bit index in the bitmap to be checked.\n de(e, t, n) {\n // Calculate hashed value h(i) = h1 + (i * h2).\n let r = e.add(t.multiply(_firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Integer.fromNumber(n)));\n // Wrap if hash value overflow 64bit.\n return 1 === r.compare(le) && (r = new _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Integer([ r.getBits(0), r.getBits(1) ], 0)), \n r.modulo(this.Ee).toNumber();\n }\n // Return whether the bit on the given index in the bitmap is set to 1.\n Ae(e) {\n return 0 != (this.bitmap[Math.floor(e / 8)] & 1 << e % 8);\n }\n mightContain(e) {\n // Empty bitmap should always return false on membership check.\n if (0 === this.Te) return !1;\n const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);\n for (let e = 0; e < this.hashCount; e++) {\n const t = this.de(n, r, e);\n if (!this.Ae(t)) return !1;\n }\n return !0;\n }\n /** Create bloom filter for testing purposes only. */ static create(e, t, n) {\n const r = e % 8 == 0 ? 0 : 8 - e % 8, i = new Uint8Array(Math.ceil(e / 8)), s = new BloomFilter(i, r, t);\n return n.forEach((e => s.insert(e))), s;\n }\n insert(e) {\n if (0 === this.Te) return;\n const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);\n for (let e = 0; e < this.hashCount; e++) {\n const t = this.de(n, r, e);\n this.Re(t);\n }\n }\n Re(e) {\n const t = Math.floor(e / 8), n = e % 8;\n this.bitmap[t] |= 1 << n;\n }\n}\n\nclass __PRIVATE_BloomFilterError extends Error {\n constructor() {\n super(...arguments), this.name = \"BloomFilterError\";\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */ class RemoteEvent {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n e, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n t, \n /**\n * A map of targets that is known to be inconsistent, and the purpose for\n * re-listening. Listens for these targets should be re-established without\n * resume tokens.\n */\n n, \n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n r, \n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n i) {\n this.snapshotVersion = e, this.targetChanges = t, this.targetMismatches = n, this.documentUpdates = r, \n this.resolvedLimboDocuments = i;\n }\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(e, t, n) {\n const r = new Map;\n return r.set(e, TargetChange.createSynthesizedTargetChangeForCurrentChange(e, t, n)), \n new RemoteEvent(SnapshotVersion.min(), r, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet());\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */ class TargetChange {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n e, \n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n t, \n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n n, \n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n r, \n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n i) {\n this.resumeToken = e, this.current = t, this.addedDocuments = n, this.modifiedDocuments = r, \n this.removedDocuments = i;\n }\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */ static createSynthesizedTargetChangeForCurrentChange(e, t, n) {\n return new TargetChange(n, t, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet());\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */ class __PRIVATE_DocumentWatchChange {\n constructor(\n /** The new document applies to all of these targets. */\n e, \n /** The new document is removed from all of these targets. */\n t, \n /** The key of the document for this change. */\n n, \n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n r) {\n this.Ve = e, this.removedTargetIds = t, this.key = n, this.me = r;\n }\n}\n\nclass __PRIVATE_ExistenceFilterChange {\n constructor(e, t) {\n this.targetId = e, this.fe = t;\n }\n}\n\nclass __PRIVATE_WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n e, \n /** The target IDs that were added/removed/set. */\n t, \n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n n = ByteString.EMPTY_BYTE_STRING\n /** An RPC error indicating why the watch failed. */ , r = null) {\n this.state = e, this.targetIds = t, this.resumeToken = n, this.cause = r;\n }\n}\n\n/** Tracks the internal state of a Watch target. */ class __PRIVATE_TargetState {\n constructor() {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n this.ge = 0, \n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n this.pe = __PRIVATE_snapshotChangesMap(), \n /** See public getters for explanations of these fields. */\n this.ye = ByteString.EMPTY_BYTE_STRING, this.we = !1, \n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n this.Se = !0;\n }\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */ get current() {\n return this.we;\n }\n /** The last resume token sent to us for this target. */ get resumeToken() {\n return this.ye;\n }\n /** Whether this target has pending target adds or target removes. */ get be() {\n return 0 !== this.ge;\n }\n /** Whether we have modified any state that should trigger a snapshot. */ get De() {\n return this.Se;\n }\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */ Ce(e) {\n e.approximateByteSize() > 0 && (this.Se = !0, this.ye = e);\n }\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */ ve() {\n let e = __PRIVATE_documentKeySet(), t = __PRIVATE_documentKeySet(), n = __PRIVATE_documentKeySet();\n return this.pe.forEach(((r, i) => {\n switch (i) {\n case 0 /* ChangeType.Added */ :\n e = e.add(r);\n break;\n\n case 2 /* ChangeType.Modified */ :\n t = t.add(r);\n break;\n\n case 1 /* ChangeType.Removed */ :\n n = n.add(r);\n break;\n\n default:\n fail();\n }\n })), new TargetChange(this.ye, this.we, e, t, n);\n }\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */ Fe() {\n this.Se = !1, this.pe = __PRIVATE_snapshotChangesMap();\n }\n Me(e, t) {\n this.Se = !0, this.pe = this.pe.insert(e, t);\n }\n xe(e) {\n this.Se = !0, this.pe = this.pe.remove(e);\n }\n Oe() {\n this.ge += 1;\n }\n Ne() {\n this.ge -= 1, __PRIVATE_hardAssert(this.ge >= 0);\n }\n Le() {\n this.Se = !0, this.we = !0;\n }\n}\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nclass __PRIVATE_WatchChangeAggregator {\n constructor(e) {\n this.Be = e, \n /** The internal state of all tracked targets. */\n this.ke = new Map, \n /** Keeps track of the documents to update since the last raised snapshot. */\n this.qe = __PRIVATE_mutableDocumentMap(), \n /** A mapping of document keys to their set of target IDs. */\n this.Qe = __PRIVATE_documentTargetMap(), \n /**\n * A map of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n this.Ke = new SortedMap(__PRIVATE_primitiveComparator);\n }\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */ $e(e) {\n for (const t of e.Ve) e.me && e.me.isFoundDocument() ? this.Ue(t, e.me) : this.We(t, e.key, e.me);\n for (const t of e.removedTargetIds) this.We(t, e.key, e.me);\n }\n /** Processes and adds the WatchTargetChange to the current set of changes. */ Ge(e) {\n this.forEachTarget(e, (t => {\n const n = this.ze(t);\n switch (e.state) {\n case 0 /* WatchTargetChangeState.NoChange */ :\n this.je(t) && n.Ce(e.resumeToken);\n break;\n\n case 1 /* WatchTargetChangeState.Added */ :\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Ne(), n.be || \n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n n.Fe(), n.Ce(e.resumeToken);\n break;\n\n case 2 /* WatchTargetChangeState.Removed */ :\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Ne(), n.be || this.removeTarget(t);\n break;\n\n case 3 /* WatchTargetChangeState.Current */ :\n this.je(t) && (n.Le(), n.Ce(e.resumeToken));\n break;\n\n case 4 /* WatchTargetChangeState.Reset */ :\n this.je(t) && (\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.He(t), n.Ce(e.resumeToken));\n break;\n\n default:\n fail();\n }\n }));\n }\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */ forEachTarget(e, t) {\n e.targetIds.length > 0 ? e.targetIds.forEach(t) : this.ke.forEach(((e, n) => {\n this.je(n) && t(n);\n }));\n }\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */ Je(e) {\n const t = e.targetId, n = e.fe.count, r = this.Ye(t);\n if (r) {\n const i = r.target;\n if (__PRIVATE_targetIsDocumentTarget(i)) if (0 === n) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const e = new DocumentKey(i.path);\n this.We(t, e, MutableDocument.newNoDocument(e, SnapshotVersion.min()));\n } else __PRIVATE_hardAssert(1 === n); else {\n const r = this.Ze(t);\n // Existence filter mismatch. Mark the documents as being in limbo, and\n // raise a snapshot with `isFromCache:true`.\n if (r !== n) {\n // Apply bloom filter to identify and mark removed documents.\n const n = this.Xe(e), i = n ? this.et(n, e, r) : 1 /* BloomFilterApplicationStatus.Skipped */;\n if (0 /* BloomFilterApplicationStatus.Success */ !== i) {\n // If bloom filter application fails, we reset the mapping and\n // trigger re-run of the query.\n this.He(t);\n const e = 2 /* BloomFilterApplicationStatus.FalsePositive */ === i ? \"TargetPurposeExistenceFilterMismatchBloom\" /* TargetPurpose.ExistenceFilterMismatchBloom */ : \"TargetPurposeExistenceFilterMismatch\" /* TargetPurpose.ExistenceFilterMismatch */;\n this.Ke = this.Ke.insert(t, e);\n }\n null == ce || ce.tt(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e, t, n, r, i) {\n var s, o, _, a, u, c;\n const l = {\n localCacheCount: e,\n existenceFilterCount: t.count,\n databaseId: n.database,\n projectId: n.projectId\n }, h = t.unchangedNames;\n h && (l.bloomFilter = {\n applied: 0 /* BloomFilterApplicationStatus.Success */ === i,\n hashCount: null !== (s = null == h ? void 0 : h.hashCount) && void 0 !== s ? s : 0,\n bitmapLength: null !== (a = null === (_ = null === (o = null == h ? void 0 : h.bits) || void 0 === o ? void 0 : o.bitmap) || void 0 === _ ? void 0 : _.length) && void 0 !== a ? a : 0,\n padding: null !== (c = null === (u = null == h ? void 0 : h.bits) || void 0 === u ? void 0 : u.padding) && void 0 !== c ? c : 0,\n mightContain: e => {\n var t;\n return null !== (t = null == r ? void 0 : r.mightContain(e)) && void 0 !== t && t;\n }\n });\n return l;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (r, e.fe, this.Be.nt(), n, i));\n }\n }\n }\n }\n /**\n * Parse the bloom filter from the \"unchanged_names\" field of an existence\n * filter.\n */ Xe(e) {\n const t = e.fe.unchangedNames;\n if (!t || !t.bits) return null;\n const {bits: {bitmap: n = \"\", padding: r = 0}, hashCount: i = 0} = t;\n let s, o;\n try {\n s = __PRIVATE_normalizeByteString(n).toUint8Array();\n } catch (e) {\n if (e instanceof __PRIVATE_Base64DecodeError) return __PRIVATE_logWarn(\"Decoding the base64 bloom filter in existence filter failed (\" + e.message + \"); ignoring the bloom filter and falling back to full re-query.\"), \n null;\n throw e;\n }\n try {\n // BloomFilter throws error if the inputs are invalid.\n o = new BloomFilter(s, r, i);\n } catch (e) {\n return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError ? \"BloomFilter error: \" : \"Applying bloom filter failed: \", e), \n null;\n }\n return 0 === o.Te ? null : o;\n }\n /**\n * Apply bloom filter to remove the deleted documents, and return the\n * application status.\n */ et(e, t, n) {\n return t.fe.count === n - this.rt(e, t.targetId) ? 0 /* BloomFilterApplicationStatus.Success */ : 2 /* BloomFilterApplicationStatus.FalsePositive */;\n }\n /**\n * Filter out removed documents based on bloom filter membership result and\n * return number of documents removed.\n */ rt(e, t) {\n const n = this.Be.getRemoteKeysForTarget(t);\n let r = 0;\n return n.forEach((n => {\n const i = this.Be.nt(), s = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;\n e.mightContain(s) || (this.We(t, n, /*updatedDocument=*/ null), r++);\n })), r;\n }\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */ it(e) {\n const t = new Map;\n this.ke.forEach(((n, r) => {\n const i = this.Ye(r);\n if (i) {\n if (n.current && __PRIVATE_targetIsDocumentTarget(i.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const t = new DocumentKey(i.target.path);\n null !== this.qe.get(t) || this.st(r, t) || this.We(r, t, MutableDocument.newNoDocument(t, e));\n }\n n.De && (t.set(r, n.ve()), n.Fe());\n }\n }));\n let n = __PRIVATE_documentKeySet();\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n \n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.Qe.forEach(((e, t) => {\n let r = !0;\n t.forEachWhile((e => {\n const t = this.Ye(e);\n return !t || \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ === t.purpose || (r = !1, \n !1);\n })), r && (n = n.add(e));\n })), this.qe.forEach(((t, n) => n.setReadTime(e)));\n const r = new RemoteEvent(e, t, this.Ke, this.qe, n);\n return this.qe = __PRIVATE_mutableDocumentMap(), this.Qe = __PRIVATE_documentTargetMap(), \n this.Ke = new SortedMap(__PRIVATE_primitiveComparator), r;\n }\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n Ue(e, t) {\n if (!this.je(e)) return;\n const n = this.st(e, t.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;\n this.ze(e).Me(t.key, n), this.qe = this.qe.insert(t.key, t), this.Qe = this.Qe.insert(t.key, this.ot(t.key).add(e));\n }\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n We(e, t, n) {\n if (!this.je(e)) return;\n const r = this.ze(e);\n this.st(e, t) ? r.Me(t, 1 /* ChangeType.Removed */) : \n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n r.xe(t), this.Qe = this.Qe.insert(t, this.ot(t).delete(e)), n && (this.qe = this.qe.insert(t, n));\n }\n removeTarget(e) {\n this.ke.delete(e);\n }\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */ Ze(e) {\n const t = this.ze(e).ve();\n return this.Be.getRemoteKeysForTarget(e).size + t.addedDocuments.size - t.removedDocuments.size;\n }\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */ Oe(e) {\n this.ze(e).Oe();\n }\n ze(e) {\n let t = this.ke.get(e);\n return t || (t = new __PRIVATE_TargetState, this.ke.set(e, t)), t;\n }\n ot(e) {\n let t = this.Qe.get(e);\n return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.Qe = this.Qe.insert(e, t)), \n t;\n }\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */ je(e) {\n const t = null !== this.Ye(e);\n return t || __PRIVATE_logDebug(\"WatchChangeAggregator\", \"Detected inactive target\", e), \n t;\n }\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */ Ye(e) {\n const t = this.ke.get(e);\n return t && t.be ? null : this.Be._t(e);\n }\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */ He(e) {\n this.ke.set(e, new __PRIVATE_TargetState);\n this.Be.getRemoteKeysForTarget(e).forEach((t => {\n this.We(e, t, /*updatedDocument=*/ null);\n }));\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */ st(e, t) {\n return this.Be.getRemoteKeysForTarget(e).has(t);\n }\n}\n\nfunction __PRIVATE_documentTargetMap() {\n return new SortedMap(DocumentKey.comparator);\n}\n\nfunction __PRIVATE_snapshotChangesMap() {\n return new SortedMap(DocumentKey.comparator);\n}\n\nconst he = (() => {\n const e = {\n asc: \"ASCENDING\",\n desc: \"DESCENDING\"\n };\n return e;\n})(), Pe = (() => {\n const e = {\n \"<\": \"LESS_THAN\",\n \"<=\": \"LESS_THAN_OR_EQUAL\",\n \">\": \"GREATER_THAN\",\n \">=\": \"GREATER_THAN_OR_EQUAL\",\n \"==\": \"EQUAL\",\n \"!=\": \"NOT_EQUAL\",\n \"array-contains\": \"ARRAY_CONTAINS\",\n in: \"IN\",\n \"not-in\": \"NOT_IN\",\n \"array-contains-any\": \"ARRAY_CONTAINS_ANY\"\n };\n return e;\n})(), Ie = (() => {\n const e = {\n and: \"AND\",\n or: \"OR\"\n };\n return e;\n})();\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nclass JsonProtoSerializer {\n constructor(e, t) {\n this.databaseId = e, this.useProto3Json = t;\n }\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction __PRIVATE_toInt32Proto(e, t) {\n return e.useProto3Json || __PRIVATE_isNullOrUndefined(t) ? t : {\n value: t\n };\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nfunction toTimestamp(e, t) {\n if (e.useProto3Json) {\n return `${new Date(1e3 * t.seconds).toISOString().replace(/\\.\\d*/, \"\").replace(\"Z\", \"\")}.${(\"000000000\" + t.nanoseconds).slice(-9)}Z`;\n }\n return {\n seconds: \"\" + t.seconds,\n nanos: t.nanoseconds\n };\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nfunction __PRIVATE_toBytes(e, t) {\n return e.useProto3Json ? t.toBase64() : t.toUint8Array();\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */ function __PRIVATE_toVersion(e, t) {\n return toTimestamp(e, t.toTimestamp());\n}\n\nfunction __PRIVATE_fromVersion(e) {\n return __PRIVATE_hardAssert(!!e), SnapshotVersion.fromTimestamp(function fromTimestamp(e) {\n const t = __PRIVATE_normalizeTimestamp(e);\n return new Timestamp(t.seconds, t.nanos);\n }(e));\n}\n\nfunction __PRIVATE_toResourceName(e, t) {\n return __PRIVATE_toResourcePath(e, t).canonicalString();\n}\n\nfunction __PRIVATE_toResourcePath(e, t) {\n const n = function __PRIVATE_fullyQualifiedPrefixPath(e) {\n return new ResourcePath([ \"projects\", e.projectId, \"databases\", e.database ]);\n }(e).child(\"documents\");\n return void 0 === t ? n : n.child(t);\n}\n\nfunction __PRIVATE_fromResourceName(e) {\n const t = ResourcePath.fromString(e);\n return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t)), t;\n}\n\nfunction __PRIVATE_toName(e, t) {\n return __PRIVATE_toResourceName(e.databaseId, t.path);\n}\n\nfunction fromName(e, t) {\n const n = __PRIVATE_fromResourceName(t);\n if (n.get(1) !== e.databaseId.projectId) throw new FirestoreError(D.INVALID_ARGUMENT, \"Tried to deserialize key from different project: \" + n.get(1) + \" vs \" + e.databaseId.projectId);\n if (n.get(3) !== e.databaseId.database) throw new FirestoreError(D.INVALID_ARGUMENT, \"Tried to deserialize key from different database: \" + n.get(3) + \" vs \" + e.databaseId.database);\n return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n));\n}\n\nfunction __PRIVATE_toQueryPath(e, t) {\n return __PRIVATE_toResourceName(e.databaseId, t);\n}\n\nfunction __PRIVATE_fromQueryPath(e) {\n const t = __PRIVATE_fromResourceName(e);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n return 4 === t.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t);\n}\n\nfunction __PRIVATE_getEncodedDatabaseId(e) {\n return new ResourcePath([ \"projects\", e.databaseId.projectId, \"databases\", e.databaseId.database ]).canonicalString();\n}\n\nfunction __PRIVATE_extractLocalPathFromResourceName(e) {\n return __PRIVATE_hardAssert(e.length > 4 && \"documents\" === e.get(4)), e.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */ function __PRIVATE_toMutationDocument(e, t, n) {\n return {\n name: __PRIVATE_toName(e, t),\n fields: n.value.mapValue.fields\n };\n}\n\nfunction __PRIVATE_fromDocument(e, t, n) {\n const r = fromName(e, t.name), i = __PRIVATE_fromVersion(t.updateTime), s = t.createTime ? __PRIVATE_fromVersion(t.createTime) : SnapshotVersion.min(), o = new ObjectValue({\n mapValue: {\n fields: t.fields\n }\n }), _ = MutableDocument.newFoundDocument(r, i, s, o);\n return n && _.setHasCommittedMutations(), n ? _.setHasCommittedMutations() : _;\n}\n\nfunction __PRIVATE_fromBatchGetDocumentsResponse(e, t) {\n return \"found\" in t ? function __PRIVATE_fromFound(e, t) {\n __PRIVATE_hardAssert(!!t.found), t.found.name, t.found.updateTime;\n const n = fromName(e, t.found.name), r = __PRIVATE_fromVersion(t.found.updateTime), i = t.found.createTime ? __PRIVATE_fromVersion(t.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({\n mapValue: {\n fields: t.found.fields\n }\n });\n return MutableDocument.newFoundDocument(n, r, i, s);\n }(e, t) : \"missing\" in t ? function __PRIVATE_fromMissing(e, t) {\n __PRIVATE_hardAssert(!!t.missing), __PRIVATE_hardAssert(!!t.readTime);\n const n = fromName(e, t.missing), r = __PRIVATE_fromVersion(t.readTime);\n return MutableDocument.newNoDocument(n, r);\n }(e, t) : fail();\n}\n\nfunction __PRIVATE_fromWatchChange(e, t) {\n let n;\n if (\"targetChange\" in t) {\n t.targetChange;\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const r = function __PRIVATE_fromWatchTargetChangeState(e) {\n return \"NO_CHANGE\" === e ? 0 /* WatchTargetChangeState.NoChange */ : \"ADD\" === e ? 1 /* WatchTargetChangeState.Added */ : \"REMOVE\" === e ? 2 /* WatchTargetChangeState.Removed */ : \"CURRENT\" === e ? 3 /* WatchTargetChangeState.Current */ : \"RESET\" === e ? 4 /* WatchTargetChangeState.Reset */ : fail();\n }(t.targetChange.targetChangeType || \"NO_CHANGE\"), i = t.targetChange.targetIds || [], s = function __PRIVATE_fromBytes(e, t) {\n return e.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t || \"string\" == typeof t), \n ByteString.fromBase64String(t || \"\")) : (__PRIVATE_hardAssert(void 0 === t || t instanceof Uint8Array), \n ByteString.fromUint8Array(t || new Uint8Array));\n }(e, t.targetChange.resumeToken), o = t.targetChange.cause, _ = o && function __PRIVATE_fromRpcStatus(e) {\n const t = void 0 === e.code ? D.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e.code);\n return new FirestoreError(t, e.message || \"\");\n }(o);\n n = new __PRIVATE_WatchTargetChange(r, i, s, _ || null);\n } else if (\"documentChange\" in t) {\n t.documentChange;\n const r = t.documentChange;\n r.document, r.document.name, r.document.updateTime;\n const i = fromName(e, r.document.name), s = __PRIVATE_fromVersion(r.document.updateTime), o = r.document.createTime ? __PRIVATE_fromVersion(r.document.createTime) : SnapshotVersion.min(), _ = new ObjectValue({\n mapValue: {\n fields: r.document.fields\n }\n }), a = MutableDocument.newFoundDocument(i, s, o, _), u = r.targetIds || [], c = r.removedTargetIds || [];\n n = new __PRIVATE_DocumentWatchChange(u, c, a.key, a);\n } else if (\"documentDelete\" in t) {\n t.documentDelete;\n const r = t.documentDelete;\n r.document;\n const i = fromName(e, r.document), s = r.readTime ? __PRIVATE_fromVersion(r.readTime) : SnapshotVersion.min(), o = MutableDocument.newNoDocument(i, s), _ = r.removedTargetIds || [];\n n = new __PRIVATE_DocumentWatchChange([], _, o.key, o);\n } else if (\"documentRemove\" in t) {\n t.documentRemove;\n const r = t.documentRemove;\n r.document;\n const i = fromName(e, r.document), s = r.removedTargetIds || [];\n n = new __PRIVATE_DocumentWatchChange([], s, i, null);\n } else {\n if (!(\"filter\" in t)) return fail();\n {\n t.filter;\n const e = t.filter;\n e.targetId;\n const {count: r = 0, unchangedNames: i} = e, s = new ExistenceFilter(r, i), o = e.targetId;\n n = new __PRIVATE_ExistenceFilterChange(o, s);\n }\n }\n return n;\n}\n\nfunction toMutation(e, t) {\n let n;\n if (t instanceof __PRIVATE_SetMutation) n = {\n update: __PRIVATE_toMutationDocument(e, t.key, t.value)\n }; else if (t instanceof __PRIVATE_DeleteMutation) n = {\n delete: __PRIVATE_toName(e, t.key)\n }; else if (t instanceof __PRIVATE_PatchMutation) n = {\n update: __PRIVATE_toMutationDocument(e, t.key, t.data),\n updateMask: __PRIVATE_toDocumentMask(t.fieldMask)\n }; else {\n if (!(t instanceof __PRIVATE_VerifyMutation)) return fail();\n n = {\n verify: __PRIVATE_toName(e, t.key)\n };\n }\n return t.fieldTransforms.length > 0 && (n.updateTransforms = t.fieldTransforms.map((e => function __PRIVATE_toFieldTransform(e, t) {\n const n = t.transform;\n if (n instanceof __PRIVATE_ServerTimestampTransform) return {\n fieldPath: t.field.canonicalString(),\n setToServerValue: \"REQUEST_TIME\"\n };\n if (n instanceof __PRIVATE_ArrayUnionTransformOperation) return {\n fieldPath: t.field.canonicalString(),\n appendMissingElements: {\n values: n.elements\n }\n };\n if (n instanceof __PRIVATE_ArrayRemoveTransformOperation) return {\n fieldPath: t.field.canonicalString(),\n removeAllFromArray: {\n values: n.elements\n }\n };\n if (n instanceof __PRIVATE_NumericIncrementTransformOperation) return {\n fieldPath: t.field.canonicalString(),\n increment: n.Ie\n };\n throw fail();\n }(0, e)))), t.precondition.isNone || (n.currentDocument = function __PRIVATE_toPrecondition(e, t) {\n return void 0 !== t.updateTime ? {\n updateTime: __PRIVATE_toVersion(e, t.updateTime)\n } : void 0 !== t.exists ? {\n exists: t.exists\n } : fail();\n }(e, t.precondition)), n;\n}\n\nfunction __PRIVATE_fromMutation(e, t) {\n const n = t.currentDocument ? function __PRIVATE_fromPrecondition(e) {\n return void 0 !== e.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)) : void 0 !== e.exists ? Precondition.exists(e.exists) : Precondition.none();\n }(t.currentDocument) : Precondition.none(), r = t.updateTransforms ? t.updateTransforms.map((t => function __PRIVATE_fromFieldTransform(e, t) {\n let n = null;\n if (\"setToServerValue\" in t) __PRIVATE_hardAssert(\"REQUEST_TIME\" === t.setToServerValue), \n n = new __PRIVATE_ServerTimestampTransform; else if (\"appendMissingElements\" in t) {\n const e = t.appendMissingElements.values || [];\n n = new __PRIVATE_ArrayUnionTransformOperation(e);\n } else if (\"removeAllFromArray\" in t) {\n const e = t.removeAllFromArray.values || [];\n n = new __PRIVATE_ArrayRemoveTransformOperation(e);\n } else \"increment\" in t ? n = new __PRIVATE_NumericIncrementTransformOperation(e, t.increment) : fail();\n const r = FieldPath$1.fromServerFormat(t.fieldPath);\n return new FieldTransform(r, n);\n }(e, t))) : [];\n if (t.update) {\n t.update.name;\n const i = fromName(e, t.update.name), s = new ObjectValue({\n mapValue: {\n fields: t.update.fields\n }\n });\n if (t.updateMask) {\n const e = function __PRIVATE_fromDocumentMask(e) {\n const t = e.fieldPaths || [];\n return new FieldMask(t.map((e => FieldPath$1.fromServerFormat(e))));\n }(t.updateMask);\n return new __PRIVATE_PatchMutation(i, s, e, n, r);\n }\n return new __PRIVATE_SetMutation(i, s, n, r);\n }\n if (t.delete) {\n const r = fromName(e, t.delete);\n return new __PRIVATE_DeleteMutation(r, n);\n }\n if (t.verify) {\n const r = fromName(e, t.verify);\n return new __PRIVATE_VerifyMutation(r, n);\n }\n return fail();\n}\n\nfunction __PRIVATE_fromWriteResults(e, t) {\n return e && e.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t), e.map((e => function __PRIVATE_fromWriteResult(e, t) {\n // NOTE: Deletes don't have an updateTime.\n let n = e.updateTime ? __PRIVATE_fromVersion(e.updateTime) : __PRIVATE_fromVersion(t);\n return n.isEqual(SnapshotVersion.min()) && (\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n n = __PRIVATE_fromVersion(t)), new MutationResult(n, e.transformResults || []);\n }(e, t)))) : [];\n}\n\nfunction __PRIVATE_toDocumentsTarget(e, t) {\n return {\n documents: [ __PRIVATE_toQueryPath(e, t.path) ]\n };\n}\n\nfunction __PRIVATE_toQueryTarget(e, t) {\n // Dissect the path into parent, collectionId, and optional key filter.\n const n = {\n structuredQuery: {}\n }, r = t.path;\n let i;\n null !== t.collectionGroup ? (i = r, n.structuredQuery.from = [ {\n collectionId: t.collectionGroup,\n allDescendants: !0\n } ]) : (i = r.popLast(), n.structuredQuery.from = [ {\n collectionId: r.lastSegment()\n } ]), n.parent = __PRIVATE_toQueryPath(e, i);\n const s = function __PRIVATE_toFilters(e) {\n if (0 === e.length) return;\n return __PRIVATE_toFilter(CompositeFilter.create(e, \"and\" /* CompositeOperator.AND */));\n }(t.filters);\n s && (n.structuredQuery.where = s);\n const o = function __PRIVATE_toOrder(e) {\n if (0 === e.length) return;\n return e.map((e => \n // visible for testing\n function __PRIVATE_toPropertyOrder(e) {\n return {\n field: __PRIVATE_toFieldPathReference(e.field),\n direction: __PRIVATE_toDirection(e.dir)\n };\n }(e)));\n }(t.orderBy);\n o && (n.structuredQuery.orderBy = o);\n const _ = __PRIVATE_toInt32Proto(e, t.limit);\n return null !== _ && (n.structuredQuery.limit = _), t.startAt && (n.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(e) {\n return {\n before: e.inclusive,\n values: e.position\n };\n }(t.startAt)), t.endAt && (n.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(e) {\n return {\n before: !e.inclusive,\n values: e.position\n };\n }(t.endAt)), {\n ut: n,\n parent: i\n };\n}\n\nfunction __PRIVATE_convertQueryTargetToQuery(e) {\n let t = __PRIVATE_fromQueryPath(e.parent);\n const n = e.structuredQuery, r = n.from ? n.from.length : 0;\n let i = null;\n if (r > 0) {\n __PRIVATE_hardAssert(1 === r);\n const e = n.from[0];\n e.allDescendants ? i = e.collectionId : t = t.child(e.collectionId);\n }\n let s = [];\n n.where && (s = function __PRIVATE_fromFilters(e) {\n const t = __PRIVATE_fromFilter(e);\n if (t instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t)) return t.getFilters();\n return [ t ];\n }(n.where));\n let o = [];\n n.orderBy && (o = function __PRIVATE_fromOrder(e) {\n return e.map((e => function __PRIVATE_fromPropertyOrder(e) {\n return new OrderBy(__PRIVATE_fromFieldPathReference(e.field), \n // visible for testing\n function __PRIVATE_fromDirection(e) {\n switch (e) {\n case \"ASCENDING\":\n return \"asc\" /* Direction.ASCENDING */;\n\n case \"DESCENDING\":\n return \"desc\" /* Direction.DESCENDING */;\n\n default:\n return;\n }\n }\n // visible for testing\n (e.direction));\n }\n // visible for testing\n (e)));\n }(n.orderBy));\n let _ = null;\n n.limit && (_ = function __PRIVATE_fromInt32Proto(e) {\n let t;\n return t = \"object\" == typeof e ? e.value : e, __PRIVATE_isNullOrUndefined(t) ? null : t;\n }(n.limit));\n let a = null;\n n.startAt && (a = function __PRIVATE_fromStartAtCursor(e) {\n const t = !!e.before, n = e.values || [];\n return new Bound(n, t);\n }(n.startAt));\n let u = null;\n return n.endAt && (u = function __PRIVATE_fromEndAtCursor(e) {\n const t = !e.before, n = e.values || [];\n return new Bound(n, t);\n }\n // visible for testing\n (n.endAt)), __PRIVATE_newQuery(t, i, o, s, _, \"F\" /* LimitType.First */ , a, u);\n}\n\nfunction __PRIVATE_toListenRequestLabels(e, t) {\n const n = function __PRIVATE_toLabel(e) {\n switch (e) {\n case \"TargetPurposeListen\" /* TargetPurpose.Listen */ :\n return null;\n\n case \"TargetPurposeExistenceFilterMismatch\" /* TargetPurpose.ExistenceFilterMismatch */ :\n return \"existence-filter-mismatch\";\n\n case \"TargetPurposeExistenceFilterMismatchBloom\" /* TargetPurpose.ExistenceFilterMismatchBloom */ :\n return \"existence-filter-mismatch-bloom\";\n\n case \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ :\n return \"limbo-document\";\n\n default:\n return fail();\n }\n }(t.purpose);\n return null == n ? null : {\n \"goog-listen-tags\": n\n };\n}\n\nfunction __PRIVATE_fromFilter(e) {\n return void 0 !== e.unaryFilter ? function __PRIVATE_fromUnaryFilter(e) {\n switch (e.unaryFilter.op) {\n case \"IS_NAN\":\n const t = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n return FieldFilter.create(t, \"==\" /* Operator.EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NULL\":\n const n = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n return FieldFilter.create(n, \"==\" /* Operator.EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n case \"IS_NOT_NAN\":\n const r = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n return FieldFilter.create(r, \"!=\" /* Operator.NOT_EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NOT_NULL\":\n const i = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n return FieldFilter.create(i, \"!=\" /* Operator.NOT_EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n default:\n return fail();\n }\n }(e) : void 0 !== e.fieldFilter ? function __PRIVATE_fromFieldFilter(e) {\n return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field), function __PRIVATE_fromOperatorName(e) {\n switch (e) {\n case \"EQUAL\":\n return \"==\" /* Operator.EQUAL */;\n\n case \"NOT_EQUAL\":\n return \"!=\" /* Operator.NOT_EQUAL */;\n\n case \"GREATER_THAN\":\n return \">\" /* Operator.GREATER_THAN */;\n\n case \"GREATER_THAN_OR_EQUAL\":\n return \">=\" /* Operator.GREATER_THAN_OR_EQUAL */;\n\n case \"LESS_THAN\":\n return \"<\" /* Operator.LESS_THAN */;\n\n case \"LESS_THAN_OR_EQUAL\":\n return \"<=\" /* Operator.LESS_THAN_OR_EQUAL */;\n\n case \"ARRAY_CONTAINS\":\n return \"array-contains\" /* Operator.ARRAY_CONTAINS */;\n\n case \"IN\":\n return \"in\" /* Operator.IN */;\n\n case \"NOT_IN\":\n return \"not-in\" /* Operator.NOT_IN */;\n\n case \"ARRAY_CONTAINS_ANY\":\n return \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */;\n\n default:\n return fail();\n }\n }(e.fieldFilter.op), e.fieldFilter.value);\n }(e) : void 0 !== e.compositeFilter ? function __PRIVATE_fromCompositeFilter(e) {\n return CompositeFilter.create(e.compositeFilter.filters.map((e => __PRIVATE_fromFilter(e))), function __PRIVATE_fromCompositeOperatorName(e) {\n switch (e) {\n case \"AND\":\n return \"and\" /* CompositeOperator.AND */;\n\n case \"OR\":\n return \"or\" /* CompositeOperator.OR */;\n\n default:\n return fail();\n }\n }(e.compositeFilter.op));\n }(e) : fail();\n}\n\nfunction __PRIVATE_toDirection(e) {\n return he[e];\n}\n\nfunction __PRIVATE_toOperatorName(e) {\n return Pe[e];\n}\n\nfunction __PRIVATE_toCompositeOperatorName(e) {\n return Ie[e];\n}\n\nfunction __PRIVATE_toFieldPathReference(e) {\n return {\n fieldPath: e.canonicalString()\n };\n}\n\nfunction __PRIVATE_fromFieldPathReference(e) {\n return FieldPath$1.fromServerFormat(e.fieldPath);\n}\n\nfunction __PRIVATE_toFilter(e) {\n return e instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(e) {\n if (\"==\" /* Operator.EQUAL */ === e.op) {\n if (__PRIVATE_isNanValue(e.value)) return {\n unaryFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: \"IS_NAN\"\n }\n };\n if (__PRIVATE_isNullValue(e.value)) return {\n unaryFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: \"IS_NULL\"\n }\n };\n } else if (\"!=\" /* Operator.NOT_EQUAL */ === e.op) {\n if (__PRIVATE_isNanValue(e.value)) return {\n unaryFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: \"IS_NOT_NAN\"\n }\n };\n if (__PRIVATE_isNullValue(e.value)) return {\n unaryFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: \"IS_NOT_NULL\"\n }\n };\n }\n return {\n fieldFilter: {\n field: __PRIVATE_toFieldPathReference(e.field),\n op: __PRIVATE_toOperatorName(e.op),\n value: e.value\n }\n };\n }(e) : e instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(e) {\n const t = e.getFilters().map((e => __PRIVATE_toFilter(e)));\n if (1 === t.length) return t[0];\n return {\n compositeFilter: {\n op: __PRIVATE_toCompositeOperatorName(e.op),\n filters: t\n }\n };\n }(e) : fail();\n}\n\nfunction __PRIVATE_toDocumentMask(e) {\n const t = [];\n return e.fields.forEach((e => t.push(e.canonicalString()))), {\n fieldPaths: t\n };\n}\n\nfunction __PRIVATE_isValidResourceName(e) {\n // Resource names have at least 4 components (project ID, database ID)\n return e.length >= 4 && \"projects\" === e.get(0) && \"databases\" === e.get(2);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */ class TargetData {\n constructor(\n /** The target being listened to. */\n e, \n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n t, \n /** The purpose of the target. */\n n, \n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n r, \n /** The latest snapshot version seen for this target. */\n i = SnapshotVersion.min()\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */ , s = SnapshotVersion.min()\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */ , o = ByteString.EMPTY_BYTE_STRING\n /**\n * The number of documents that last matched the query at the resume token or\n * read time. Documents are counted only when making a listen request with\n * resume token or read time, otherwise, keep it null.\n */ , _ = null) {\n this.target = e, this.targetId = t, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i, \n this.lastLimboFreeSnapshotVersion = s, this.resumeToken = o, this.expectedCount = _;\n }\n /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(e) {\n return new TargetData(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);\n }\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */ withResumeToken(e, t) {\n return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, t, this.lastLimboFreeSnapshotVersion, e, \n /* expectedCount= */ null);\n }\n /**\n * Creates a new target data instance with an updated expected count.\n */ withExpectedCount(e) {\n return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e);\n }\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */ withLastLimboFreeSnapshotVersion(e) {\n return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Serializer for values stored in the LocalStore. */ class __PRIVATE_LocalSerializer {\n constructor(e) {\n this.ct = e;\n }\n}\n\n/** Decodes a remote document from storage locally to a Document. */ function __PRIVATE_fromDbRemoteDocument(e, t) {\n let n;\n if (t.document) n = __PRIVATE_fromDocument(e.ct, t.document, !!t.hasCommittedMutations); else if (t.noDocument) {\n const e = DocumentKey.fromSegments(t.noDocument.path), r = __PRIVATE_fromDbTimestamp(t.noDocument.readTime);\n n = MutableDocument.newNoDocument(e, r), t.hasCommittedMutations && n.setHasCommittedMutations();\n } else {\n if (!t.unknownDocument) return fail();\n {\n const e = DocumentKey.fromSegments(t.unknownDocument.path), r = __PRIVATE_fromDbTimestamp(t.unknownDocument.version);\n n = MutableDocument.newUnknownDocument(e, r);\n }\n }\n return t.readTime && n.setReadTime(function __PRIVATE_fromDbTimestampKey(e) {\n const t = new Timestamp(e[0], e[1]);\n return SnapshotVersion.fromTimestamp(t);\n }(t.readTime)), n;\n}\n\n/** Encodes a document for storage locally. */ function __PRIVATE_toDbRemoteDocument(e, t) {\n const n = t.key, r = {\n prefixPath: n.getCollectionPath().popLast().toArray(),\n collectionGroup: n.collectionGroup,\n documentId: n.path.lastSegment(),\n readTime: __PRIVATE_toDbTimestampKey(t.readTime),\n hasCommittedMutations: t.hasCommittedMutations\n };\n if (t.isFoundDocument()) r.document = function __PRIVATE_toDocument(e, t) {\n return {\n name: __PRIVATE_toName(e, t.key),\n fields: t.data.value.mapValue.fields,\n updateTime: toTimestamp(e, t.version.toTimestamp()),\n createTime: toTimestamp(e, t.createTime.toTimestamp())\n };\n }(e.ct, t); else if (t.isNoDocument()) r.noDocument = {\n path: n.path.toArray(),\n readTime: __PRIVATE_toDbTimestamp(t.version)\n }; else {\n if (!t.isUnknownDocument()) return fail();\n r.unknownDocument = {\n path: n.path.toArray(),\n version: __PRIVATE_toDbTimestamp(t.version)\n };\n }\n return r;\n}\n\nfunction __PRIVATE_toDbTimestampKey(e) {\n const t = e.toTimestamp();\n return [ t.seconds, t.nanoseconds ];\n}\n\nfunction __PRIVATE_toDbTimestamp(e) {\n const t = e.toTimestamp();\n return {\n seconds: t.seconds,\n nanoseconds: t.nanoseconds\n };\n}\n\nfunction __PRIVATE_fromDbTimestamp(e) {\n const t = new Timestamp(e.seconds, e.nanoseconds);\n return SnapshotVersion.fromTimestamp(t);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n/** Decodes a DbMutationBatch into a MutationBatch */\nfunction __PRIVATE_fromDbMutationBatch(e, t) {\n const n = (t.baseMutations || []).map((t => __PRIVATE_fromMutation(e.ct, t)));\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let e = 0; e < t.mutations.length - 1; ++e) {\n const n = t.mutations[e];\n if (e + 1 < t.mutations.length && void 0 !== t.mutations[e + 1].transform) {\n const r = t.mutations[e + 1];\n n.updateTransforms = r.transform.fieldTransforms, t.mutations.splice(e + 1, 1), \n ++e;\n }\n }\n const r = t.mutations.map((t => __PRIVATE_fromMutation(e.ct, t))), i = Timestamp.fromMillis(t.localWriteTimeMs);\n return new MutationBatch(t.batchId, i, n, r);\n}\n\n/** Decodes a DbTarget into TargetData */ function __PRIVATE_fromDbTarget(e) {\n const t = __PRIVATE_fromDbTimestamp(e.readTime), n = void 0 !== e.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion) : SnapshotVersion.min();\n let r;\n return r = \n /**\n * A helper function for figuring out what kind of query has been stored.\n */\n function __PRIVATE_isDocumentQuery(e) {\n return void 0 !== e.documents;\n }\n /** Encodes a DbBundle to a BundleMetadata object. */ (e.query) ? function __PRIVATE_fromDocumentsTarget(e) {\n return __PRIVATE_hardAssert(1 === e.documents.length), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0])));\n }(e.query) : function __PRIVATE_fromQueryTarget(e) {\n return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e));\n }(e.query), new TargetData(r, e.targetId, \"TargetPurposeListen\" /* TargetPurpose.Listen */ , e.lastListenSequenceNumber, t, n, ByteString.fromBase64String(e.resumeToken));\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */ function __PRIVATE_toDbTarget(e, t) {\n const n = __PRIVATE_toDbTimestamp(t.snapshotVersion), r = __PRIVATE_toDbTimestamp(t.lastLimboFreeSnapshotVersion);\n let i;\n i = __PRIVATE_targetIsDocumentTarget(t.target) ? __PRIVATE_toDocumentsTarget(e.ct, t.target) : __PRIVATE_toQueryTarget(e.ct, t.target).ut;\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const s = t.resumeToken.toBase64();\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: t.targetId,\n canonicalId: __PRIVATE_canonifyTarget(t.target),\n readTime: n,\n resumeToken: s,\n lastListenSequenceNumber: t.sequenceNumber,\n lastLimboFreeSnapshotVersion: r,\n query: i\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nfunction __PRIVATE_fromBundledQuery(e) {\n const t = __PRIVATE_convertQueryTargetToQuery({\n parent: e.parent,\n structuredQuery: e.structuredQuery\n });\n return \"LAST\" === e.limitType ? __PRIVATE_queryWithLimit(t, t.limit, \"L\" /* LimitType.Last */) : t;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nfunction __PRIVATE_fromDbDocumentOverlay(e, t) {\n return new Overlay(t.largestBatchId, __PRIVATE_fromMutation(e.ct, t.overlayMutation));\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nfunction __PRIVATE_toDbDocumentOverlayKey(e, t) {\n const n = t.path.lastSegment();\n return [ e, __PRIVATE_encodeResourcePath(t.path.popLast()), n ];\n}\n\nfunction __PRIVATE_toDbIndexState(e, t, n, r) {\n return {\n indexId: e,\n uid: t,\n sequenceNumber: n,\n readTime: __PRIVATE_toDbTimestamp(r.readTime),\n documentKey: __PRIVATE_encodeResourcePath(r.documentKey.path),\n largestBatchId: r.largestBatchId\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_IndexedDbBundleCache {\n getBundleMetadata(e, t) {\n return __PRIVATE_bundlesStore(e).get(t).next((e => {\n if (e) return function __PRIVATE_fromDbBundle(e) {\n return {\n id: e.bundleId,\n createTime: __PRIVATE_fromDbTimestamp(e.createTime),\n version: e.version\n };\n }\n /** Encodes a BundleMetadata to a DbBundle. */ (e);\n }));\n }\n saveBundleMetadata(e, t) {\n return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e) {\n return {\n bundleId: e.id,\n createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)),\n version: e.version\n };\n }\n /** Encodes a DbNamedQuery to a NamedQuery. */ (t));\n }\n getNamedQuery(e, t) {\n return __PRIVATE_namedQueriesStore(e).get(t).next((e => {\n if (e) return function __PRIVATE_fromDbNamedQuery(e) {\n return {\n name: e.name,\n query: __PRIVATE_fromBundledQuery(e.bundledQuery),\n readTime: __PRIVATE_fromDbTimestamp(e.readTime)\n };\n }\n /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ (e);\n }));\n }\n saveNamedQuery(e, t) {\n return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e) {\n return {\n name: e.name,\n readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)),\n bundledQuery: e.bundledQuery\n };\n }(t));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */ function __PRIVATE_bundlesStore(e) {\n return __PRIVATE_getStore(e, \"bundles\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */ function __PRIVATE_namedQueriesStore(e) {\n return __PRIVATE_getStore(e, \"namedQueries\");\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */ class __PRIVATE_IndexedDbDocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(e, t) {\n this.serializer = e, this.userId = t;\n }\n static lt(e, t) {\n const n = t.uid || \"\";\n return new __PRIVATE_IndexedDbDocumentOverlayCache(e, n);\n }\n getOverlay(e, t) {\n return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t)).next((e => e ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e) : null));\n }\n getOverlays(e, t) {\n const n = __PRIVATE_newOverlayMap();\n return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => {\n null !== e && n.set(t, e);\n })))).next((() => n));\n }\n saveOverlays(e, t, n) {\n const r = [];\n return n.forEach(((n, i) => {\n const s = new Overlay(t, i);\n r.push(this.ht(e, s));\n })), PersistencePromise.waitFor(r);\n }\n removeOverlaysForBatchId(e, t, n) {\n const r = new Set;\n // Get the set of unique collection paths.\n t.forEach((e => r.add(__PRIVATE_encodeResourcePath(e.getCollectionPath()))));\n const i = [];\n return r.forEach((t => {\n const r = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, n + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n i.push(__PRIVATE_documentOverlayStore(e).H(\"collectionPathOverlayIndex\", r));\n })), PersistencePromise.waitFor(i);\n }\n getOverlaysForCollection(e, t, n) {\n const r = __PRIVATE_newOverlayMap(), i = __PRIVATE_encodeResourcePath(t), s = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return __PRIVATE_documentOverlayStore(e).W(\"collectionPathOverlayIndex\", s).next((e => {\n for (const t of e) {\n const e = __PRIVATE_fromDbDocumentOverlay(this.serializer, t);\n r.set(e.getKey(), e);\n }\n return r;\n }));\n }\n getOverlaysForCollectionGroup(e, t, n, r) {\n const i = __PRIVATE_newOverlayMap();\n let s;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const o = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return __PRIVATE_documentOverlayStore(e).Y({\n index: \"collectionGroupOverlayIndex\",\n range: o\n }, ((e, t, n) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const o = __PRIVATE_fromDbDocumentOverlay(this.serializer, t);\n i.size() < r || o.largestBatchId === s ? (i.set(o.getKey(), o), s = o.largestBatchId) : n.done();\n })).next((() => i));\n }\n ht(e, t) {\n return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e, t, n) {\n const [r, i, s] = __PRIVATE_toDbDocumentOverlayKey(t, n.mutation.key);\n return {\n userId: t,\n collectionPath: i,\n documentId: s,\n collectionGroup: n.mutation.key.getCollectionGroup(),\n largestBatchId: n.largestBatchId,\n overlayMutation: toMutation(e.ct, n.mutation)\n };\n }(this.serializer, this.userId, t));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */ function __PRIVATE_documentOverlayStore(e) {\n return __PRIVATE_getStore(e, \"documentOverlays\");\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n/** Firestore index value writer. */\nclass __PRIVATE_FirestoreIndexValueWriter {\n constructor() {}\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n // As an example, consider the resulting encoding for:\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n /** Writes an index value. */\n Pt(e, t) {\n this.It(e, t), \n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n t.Tt();\n }\n It(e, t) {\n if (\"nullValue\" in e) this.Et(t, 5); else if (\"booleanValue\" in e) this.Et(t, 10), \n t.dt(e.booleanValue ? 1 : 0); else if (\"integerValue\" in e) this.Et(t, 15), t.dt(__PRIVATE_normalizeNumber(e.integerValue)); else if (\"doubleValue\" in e) {\n const n = __PRIVATE_normalizeNumber(e.doubleValue);\n isNaN(n) ? this.Et(t, 13) : (this.Et(t, 15), __PRIVATE_isNegativeZero(n) ? \n // -0.0, 0 and 0.0 are all considered the same\n t.dt(0) : t.dt(n));\n } else if (\"timestampValue\" in e) {\n const n = e.timestampValue;\n this.Et(t, 20), \"string\" == typeof n ? t.At(n) : (t.At(`${n.seconds || \"\"}`), t.dt(n.nanos || 0));\n } else if (\"stringValue\" in e) this.Rt(e.stringValue, t), this.Vt(t); else if (\"bytesValue\" in e) this.Et(t, 30), \n t.ft(__PRIVATE_normalizeByteString(e.bytesValue)), this.Vt(t); else if (\"referenceValue\" in e) this.gt(e.referenceValue, t); else if (\"geoPointValue\" in e) {\n const n = e.geoPointValue;\n this.Et(t, 45), t.dt(n.latitude || 0), t.dt(n.longitude || 0);\n } else \"mapValue\" in e ? __PRIVATE_isMaxValue(e) ? this.Et(t, Number.MAX_SAFE_INTEGER) : (this.yt(e.mapValue, t), \n this.Vt(t)) : \"arrayValue\" in e ? (this.wt(e.arrayValue, t), this.Vt(t)) : fail();\n }\n Rt(e, t) {\n this.Et(t, 25), this.St(e, t);\n }\n St(e, t) {\n t.At(e);\n }\n yt(e, t) {\n const n = e.fields || {};\n this.Et(t, 55);\n for (const e of Object.keys(n)) this.Rt(e, t), this.It(n[e], t);\n }\n wt(e, t) {\n const n = e.values || [];\n this.Et(t, 50);\n for (const e of n) this.It(e, t);\n }\n gt(e, t) {\n this.Et(t, 37);\n DocumentKey.fromName(e).path.forEach((e => {\n this.Et(t, 60), this.St(e, t);\n }));\n }\n Et(e, t) {\n e.dt(t);\n }\n Vt(e) {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n e.dt(2);\n }\n}\n\n__PRIVATE_FirestoreIndexValueWriter.bt = new __PRIVATE_FirestoreIndexValueWriter;\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nfunction __PRIVATE_numberOfLeadingZerosInByte(e) {\n if (0 === e) return 8;\n let t = 0;\n return e >> 4 == 0 && (\n // Test if the first four bits are zero.\n t += 4, e <<= 4), e >> 6 == 0 && (\n // Test if the first two (or next two) bits are zero.\n t += 2, e <<= 2), e >> 7 == 0 && (\n // Test if the remaining bit is zero.\n t += 1), t;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction __PRIVATE_unsignedNumLength(e) {\n // This is just the number of bytes for the unsigned representation of the number.\n const t = 64 - function __PRIVATE_numberOfLeadingZeros(e) {\n let t = 0;\n for (let n = 0; n < 8; ++n) {\n const r = __PRIVATE_numberOfLeadingZerosInByte(255 & e[n]);\n if (t += r, 8 !== r) break;\n }\n return t;\n }(e);\n return Math.ceil(t / 8);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */ class __PRIVATE_OrderedCodeWriter {\n constructor() {\n this.buffer = new Uint8Array(1024), this.position = 0;\n }\n Dt(e) {\n const t = e[Symbol.iterator]();\n let n = t.next();\n for (;!n.done; ) this.Ct(n.value), n = t.next();\n this.vt();\n }\n Ft(e) {\n const t = e[Symbol.iterator]();\n let n = t.next();\n for (;!n.done; ) this.Mt(n.value), n = t.next();\n this.xt();\n }\n /** Writes utf8 bytes into this byte sequence, ascending. */ Ot(e) {\n for (const t of e) {\n const e = t.charCodeAt(0);\n if (e < 128) this.Ct(e); else if (e < 2048) this.Ct(960 | e >>> 6), this.Ct(128 | 63 & e); else if (t < \"\\ud800\" || \"\\udbff\" < t) this.Ct(480 | e >>> 12), \n this.Ct(128 | 63 & e >>> 6), this.Ct(128 | 63 & e); else {\n const e = t.codePointAt(0);\n this.Ct(240 | e >>> 18), this.Ct(128 | 63 & e >>> 12), this.Ct(128 | 63 & e >>> 6), \n this.Ct(128 | 63 & e);\n }\n }\n this.vt();\n }\n /** Writes utf8 bytes into this byte sequence, descending */ Nt(e) {\n for (const t of e) {\n const e = t.charCodeAt(0);\n if (e < 128) this.Mt(e); else if (e < 2048) this.Mt(960 | e >>> 6), this.Mt(128 | 63 & e); else if (t < \"\\ud800\" || \"\\udbff\" < t) this.Mt(480 | e >>> 12), \n this.Mt(128 | 63 & e >>> 6), this.Mt(128 | 63 & e); else {\n const e = t.codePointAt(0);\n this.Mt(240 | e >>> 18), this.Mt(128 | 63 & e >>> 12), this.Mt(128 | 63 & e >>> 6), \n this.Mt(128 | 63 & e);\n }\n }\n this.xt();\n }\n Lt(e) {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const t = this.Bt(e), n = __PRIVATE_unsignedNumLength(t);\n this.kt(1 + n), this.buffer[this.position++] = 255 & n;\n // Write the length\n for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = 255 & t[e];\n }\n qt(e) {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const t = this.Bt(e), n = __PRIVATE_unsignedNumLength(t);\n this.kt(1 + n), this.buffer[this.position++] = ~(255 & n);\n // Write the length\n for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = ~(255 & t[e]);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */ Qt() {\n this.Kt(255), this.Kt(255);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */ $t() {\n this.Ut(255), this.Ut(255);\n }\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */ reset() {\n this.position = 0;\n }\n seed(e) {\n this.kt(e.length), this.buffer.set(e, this.position), this.position += e.length;\n }\n /** Makes a copy of the encoded bytes in this buffer. */ Wt() {\n return this.buffer.slice(0, this.position);\n }\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */ Bt(e) {\n const t = \n /** Converts a JavaScript number to a byte array (using big endian encoding). */\n function __PRIVATE_doubleToLongBits(e) {\n const t = new DataView(new ArrayBuffer(8));\n return t.setFloat64(0, e, /* littleEndian= */ !1), new Uint8Array(t.buffer);\n }(e), n = 0 != (128 & t[0]);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n // Revert the two complement to get natural ordering\n t[0] ^= n ? 255 : 128;\n for (let e = 1; e < t.length; ++e) t[e] ^= n ? 255 : 0;\n return t;\n }\n /** Writes a single byte ascending to the buffer. */ Ct(e) {\n const t = 255 & e;\n 0 === t ? (this.Kt(0), this.Kt(255)) : 255 === t ? (this.Kt(255), this.Kt(0)) : this.Kt(t);\n }\n /** Writes a single byte descending to the buffer. */ Mt(e) {\n const t = 255 & e;\n 0 === t ? (this.Ut(0), this.Ut(255)) : 255 === t ? (this.Ut(255), this.Ut(0)) : this.Ut(e);\n }\n vt() {\n this.Kt(0), this.Kt(1);\n }\n xt() {\n this.Ut(0), this.Ut(1);\n }\n Kt(e) {\n this.kt(1), this.buffer[this.position++] = e;\n }\n Ut(e) {\n this.kt(1), this.buffer[this.position++] = ~e;\n }\n kt(e) {\n const t = e + this.position;\n if (t <= this.buffer.length) return;\n // Try doubling.\n let n = 2 * this.buffer.length;\n // Still not big enough? Just allocate the right size.\n n < t && (n = t);\n // Create the new buffer.\n const r = new Uint8Array(n);\n r.set(this.buffer), // copy old data\n this.buffer = r;\n }\n}\n\nclass __PRIVATE_AscendingIndexByteEncoder {\n constructor(e) {\n this.Gt = e;\n }\n ft(e) {\n this.Gt.Dt(e);\n }\n At(e) {\n this.Gt.Ot(e);\n }\n dt(e) {\n this.Gt.Lt(e);\n }\n Tt() {\n this.Gt.Qt();\n }\n}\n\nclass __PRIVATE_DescendingIndexByteEncoder {\n constructor(e) {\n this.Gt = e;\n }\n ft(e) {\n this.Gt.Ft(e);\n }\n At(e) {\n this.Gt.Nt(e);\n }\n dt(e) {\n this.Gt.qt(e);\n }\n Tt() {\n this.Gt.$t();\n }\n}\n\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */ class __PRIVATE_IndexByteEncoder {\n constructor() {\n this.Gt = new __PRIVATE_OrderedCodeWriter, this.zt = new __PRIVATE_AscendingIndexByteEncoder(this.Gt), \n this.jt = new __PRIVATE_DescendingIndexByteEncoder(this.Gt);\n }\n seed(e) {\n this.Gt.seed(e);\n }\n Ht(e) {\n return 0 /* IndexKind.ASCENDING */ === e ? this.zt : this.jt;\n }\n Wt() {\n return this.Gt.Wt();\n }\n reset() {\n this.Gt.reset();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Represents an index entry saved by the SDK in persisted storage. */ class __PRIVATE_IndexEntry {\n constructor(e, t, n, r) {\n this.indexId = e, this.documentKey = t, this.arrayValue = n, this.directionalValue = r;\n }\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */ Jt() {\n const e = this.directionalValue.length, t = 0 === e || 255 === this.directionalValue[e - 1] ? e + 1 : e, n = new Uint8Array(t);\n return n.set(this.directionalValue, 0), t !== e ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1], \n new __PRIVATE_IndexEntry(this.indexId, this.documentKey, this.arrayValue, n);\n }\n}\n\nfunction __PRIVATE_indexEntryComparator(e, t) {\n let n = e.indexId - t.indexId;\n return 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.arrayValue, t.arrayValue), \n 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.directionalValue, t.directionalValue), \n 0 !== n ? n : DocumentKey.comparator(e.documentKey, t.documentKey)));\n}\n\nfunction __PRIVATE_compareByteArrays(e, t) {\n for (let n = 0; n < e.length && n < t.length; ++n) {\n const r = e[n] - t[n];\n if (0 !== r) return r;\n }\n return e.length - t.length;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */ class __PRIVATE_TargetIndexMatcher {\n constructor(e) {\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n this.Yt = new SortedSet(((e, t) => FieldPath$1.comparator(e.field, t.field))), this.collectionId = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment(), \n this.Zt = e.orderBy, this.Xt = [];\n for (const t of e.filters) {\n const e = t;\n e.isInequality() ? this.Yt = this.Yt.add(e) : this.Xt.push(e);\n }\n }\n get en() {\n return this.Yt.size > 1;\n }\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */ tn(e) {\n if (__PRIVATE_hardAssert(e.collectionGroup === this.collectionId), this.en) \n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return !1;\n // If there is an array element, find a matching filter.\n const t = __PRIVATE_fieldIndexGetArraySegment(e);\n if (void 0 !== t && !this.nn(t)) return !1;\n const n = __PRIVATE_fieldIndexGetDirectionalSegments(e);\n let r = new Set, i = 0, s = 0;\n // Process all equalities first. Equalities can appear out of order.\n for (;i < n.length && this.nn(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString());\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (i === n.length) return !0;\n if (this.Yt.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const e = this.Yt.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!r.has(e.field.canonicalString())) {\n const t = n[i];\n if (!this.rn(e, t) || !this.sn(this.Zt[s++], t)) return !1;\n }\n ++i;\n }\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (;i < n.length; ++i) {\n const e = n[i];\n if (s >= this.Zt.length || !this.sn(this.Zt[s++], e)) return !1;\n }\n return !0;\n }\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */ on() {\n if (this.en) return null;\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let e = new SortedSet(FieldPath$1.comparator);\n const t = [];\n for (const n of this.Xt) {\n if (n.field.isKeyField()) continue;\n if (\"array-contains\" /* Operator.ARRAY_CONTAINS */ === n.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === n.op) t.push(new IndexSegment(n.field, 2 /* IndexKind.CONTAINS */)); else {\n if (e.has(n.field)) continue;\n e = e.add(n.field), t.push(new IndexSegment(n.field, 0 /* IndexKind.ASCENDING */));\n }\n }\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const n of this.Zt) \n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n n.field.isKeyField() || e.has(n.field) || (e = e.add(n.field), t.push(new IndexSegment(n.field, \"asc\" /* Direction.ASCENDING */ === n.dir ? 0 /* IndexKind.ASCENDING */ : 1 /* IndexKind.DESCENDING */)));\n return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, t, IndexState.empty());\n }\n nn(e) {\n for (const t of this.Xt) if (this.rn(t, e)) return !0;\n return !1;\n }\n rn(e, t) {\n if (void 0 === e || !e.field.isEqual(t.fieldPath)) return !1;\n const n = \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e.op;\n return 2 /* IndexKind.CONTAINS */ === t.kind === n;\n }\n sn(e, t) {\n return !!e.field.isEqual(t.fieldPath) && (0 /* IndexKind.ASCENDING */ === t.kind && \"asc\" /* Direction.ASCENDING */ === e.dir || 1 /* IndexKind.DESCENDING */ === t.kind && \"desc\" /* Direction.DESCENDING */ === e.dir);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */ function __PRIVATE_computeInExpansion(e) {\n var t, n;\n if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n e instanceof FieldFilter) {\n if (e instanceof __PRIVATE_InFilter) {\n const r = (null === (n = null === (t = e.value.arrayValue) || void 0 === t ? void 0 : t.values) || void 0 === n ? void 0 : n.map((t => FieldFilter.create(e.field, \"==\" /* Operator.EQUAL */ , t)))) || [];\n return CompositeFilter.create(r, \"or\" /* CompositeOperator.OR */);\n }\n // We have reached other kinds of field filters.\n return e;\n }\n // We have a composite filter.\n const r = e.filters.map((e => __PRIVATE_computeInExpansion(e)));\n return CompositeFilter.create(r, e.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *
Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */ function __PRIVATE_getDnfTerms(e) {\n if (0 === e.getFilters().length) return [];\n const t = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e));\n return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t)), __PRIVATE_isSingleFieldFilter(t) || __PRIVATE_isFlatConjunction(t) ? [ t ] : t.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function __PRIVATE_isSingleFieldFilter(e) {\n return e instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */ function __PRIVATE_isFlatConjunction(e) {\n return e instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e);\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *
In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *
For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */ function __PRIVATE_isDisjunctiveNormalForm(e) {\n return __PRIVATE_isSingleFieldFilter(e) || __PRIVATE_isFlatConjunction(e) || \n /**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\n function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e) {\n if (e instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e)) {\n for (const t of e.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t) && !__PRIVATE_isFlatConjunction(t)) return !1;\n return !0;\n }\n return !1;\n }(e);\n}\n\nfunction __PRIVATE_computeDistributedNormalForm(e) {\n if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n e instanceof FieldFilter) return e;\n if (1 === e.filters.length) return __PRIVATE_computeDistributedNormalForm(e.filters[0]);\n // Compute DNF for each of the subfilters first\n const t = e.filters.map((e => __PRIVATE_computeDistributedNormalForm(e)));\n let n = CompositeFilter.create(t, e.op);\n return n = __PRIVATE_applyAssociation(n), __PRIVATE_isDisjunctiveNormalForm(n) ? n : (__PRIVATE_hardAssert(n instanceof CompositeFilter), \n __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n)), __PRIVATE_hardAssert(n.filters.length > 1), \n n.filters.reduce(((e, t) => __PRIVATE_applyDistribution(e, t))));\n}\n\nfunction __PRIVATE_applyDistribution(e, t) {\n let n;\n return __PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n __PRIVATE_hardAssert(t instanceof FieldFilter || t instanceof CompositeFilter), \n // FieldFilter FieldFilter\n n = e instanceof FieldFilter ? t instanceof FieldFilter ? function __PRIVATE_applyDistributionFieldFilters(e, t) {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([ e, t ], \"and\" /* CompositeOperator.AND */);\n }(e, t) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) : t instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t, e) : function __PRIVATE_applyDistributionCompositeFilters(e, t) {\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n // Case 1 is a merge.\n if (__PRIVATE_hardAssert(e.filters.length > 0 && t.filters.length > 0), __PRIVATE_compositeFilterIsConjunction(e) && __PRIVATE_compositeFilterIsConjunction(t)) return __PRIVATE_compositeFilterWithAddedFilters(e, t.getFilters());\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const n = __PRIVATE_compositeFilterIsDisjunction(e) ? e : t, r = __PRIVATE_compositeFilterIsDisjunction(e) ? t : e, i = n.filters.map((e => __PRIVATE_applyDistribution(e, r)));\n return CompositeFilter.create(i, \"or\" /* CompositeOperator.OR */);\n }(e, t), __PRIVATE_applyAssociation(n);\n}\n\nfunction __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (__PRIVATE_compositeFilterIsConjunction(t)) \n // Case 1\n return __PRIVATE_compositeFilterWithAddedFilters(t, e.getFilters());\n {\n // Case 2\n const n = t.filters.map((t => __PRIVATE_applyDistribution(e, t)));\n return CompositeFilter.create(n, \"or\" /* CompositeOperator.OR */);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *
\n *
A | (B | C) == (A | B) | C == (A | B | C)\n *
A & (B & C) == (A & B) & C == (A & B & C)\n *
\n *\n *
For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */ function __PRIVATE_applyAssociation(e) {\n if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n e instanceof FieldFilter) return e;\n const t = e.getFilters();\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (1 === t.length) return __PRIVATE_applyAssociation(t[0]);\n // Associativity applied to a flat composite filter results is itself.\n if (__PRIVATE_compositeFilterIsFlat(e)) return e;\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const n = t.map((e => __PRIVATE_applyAssociation(e))), r = [];\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n return n.forEach((t => {\n t instanceof FieldFilter ? r.push(t) : t instanceof CompositeFilter && (t.op === e.op ? \n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n r.push(...t.filters) : \n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n r.push(t));\n })), 1 === r.length ? r[0] : CompositeFilter.create(r, e.op);\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of IndexManager.\n */ class __PRIVATE_MemoryIndexManager {\n constructor() {\n this._n = new __PRIVATE_MemoryCollectionParentIndex;\n }\n addToCollectionParentIndex(e, t) {\n return this._n.add(t), PersistencePromise.resolve();\n }\n getCollectionParents(e, t) {\n return PersistencePromise.resolve(this._n.getEntries(t));\n }\n addFieldIndex(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n deleteFieldIndex(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n deleteAllFieldIndexes(e) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n createTargetIndexes(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n getDocumentsMatchingTarget(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n getIndexType(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(0 /* IndexType.NONE */);\n }\n getFieldIndexes(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve([]);\n }\n getNextCollectionGroupToUpdate(e) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n getMinOffset(e, t) {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n getMinOffsetFromCollectionGroup(e, t) {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n updateCollectionGroup(e, t, n) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n updateIndexEntries(e, t) {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */ class __PRIVATE_MemoryCollectionParentIndex {\n constructor() {\n this.index = {};\n }\n // Returns false if the entry already existed.\n add(e) {\n const t = e.lastSegment(), n = e.popLast(), r = this.index[t] || new SortedSet(ResourcePath.comparator), i = !r.has(n);\n return this.index[t] = r.add(n), i;\n }\n has(e) {\n const t = e.lastSegment(), n = e.popLast(), r = this.index[t];\n return r && r.has(n);\n }\n getEntries(e) {\n return (this.index[e] || new SortedSet(ResourcePath.comparator)).toArray();\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Te = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nclass __PRIVATE_IndexedDbIndexManager {\n constructor(e, t) {\n this.databaseId = t, \n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n this.an = new __PRIVATE_MemoryCollectionParentIndex, \n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n this.un = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), ((e, t) => __PRIVATE_targetEquals(e, t))), \n this.uid = e.uid || \"\";\n }\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */ addToCollectionParentIndex(e, t) {\n if (!this.an.has(t)) {\n const n = t.lastSegment(), r = t.popLast();\n e.addOnCommittedListener((() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.an.add(t);\n }));\n const i = {\n collectionId: n,\n parent: __PRIVATE_encodeResourcePath(r)\n };\n return __PRIVATE_collectionParentsStore(e).put(i);\n }\n return PersistencePromise.resolve();\n }\n getCollectionParents(e, t) {\n const n = [], r = IDBKeyRange.bound([ t, \"\" ], [ __PRIVATE_immediateSuccessor(t), \"\" ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return __PRIVATE_collectionParentsStore(e).W(r).next((e => {\n for (const r of e) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (r.collectionId !== t) break;\n n.push(__PRIVATE_decodeResourcePath(r.parent));\n }\n return n;\n }));\n }\n addFieldIndex(e, t) {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const n = __PRIVATE_indexConfigurationStore(e), r = function __PRIVATE_toDbIndexConfiguration(e) {\n return {\n indexId: e.indexId,\n collectionGroup: e.collectionGroup,\n fields: e.fields.map((e => [ e.fieldPath.canonicalString(), e.kind ]))\n };\n }(t);\n delete r.indexId;\n // `indexId` is auto-populated by IndexedDb\n const i = n.add(r);\n if (t.indexState) {\n const n = __PRIVATE_indexStateStore(e);\n return i.next((e => {\n n.put(__PRIVATE_toDbIndexState(e, this.uid, t.indexState.sequenceNumber, t.indexState.offset));\n }));\n }\n return i.next();\n }\n deleteFieldIndex(e, t) {\n const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e), i = __PRIVATE_indexEntriesStore(e);\n return n.delete(t.indexId).next((() => r.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0))));\n }\n deleteAllFieldIndexes(e) {\n const t = __PRIVATE_indexConfigurationStore(e), n = __PRIVATE_indexEntriesStore(e), r = __PRIVATE_indexStateStore(e);\n return t.H().next((() => n.H())).next((() => r.H()));\n }\n createTargetIndexes(e, t) {\n return PersistencePromise.forEach(this.cn(t), (t => this.getIndexType(e, t).next((n => {\n if (0 /* IndexType.NONE */ === n || 1 /* IndexType.PARTIAL */ === n) {\n const n = new __PRIVATE_TargetIndexMatcher(t).on();\n if (null != n) return this.addFieldIndex(e, n);\n }\n }))));\n }\n getDocumentsMatchingTarget(e, t) {\n const n = __PRIVATE_indexEntriesStore(e);\n let r = !0;\n const i = new Map;\n return PersistencePromise.forEach(this.cn(t), (t => this.ln(e, t).next((e => {\n r && (r = !!e), i.set(t, e);\n })))).next((() => {\n if (r) {\n let e = __PRIVATE_documentKeySet();\n const r = [];\n return PersistencePromise.forEach(i, ((i, s) => {\n __PRIVATE_logDebug(\"IndexedDbIndexManager\", `Using index ${function __PRIVATE_fieldIndexToString(e) {\n return `id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e => `${e.fieldPath}:${e.kind}`)).join(\",\")}`;\n }(i)} to execute ${__PRIVATE_canonifyTarget(t)}`);\n const o = function __PRIVATE_targetGetArrayValues(e, t) {\n const n = __PRIVATE_fieldIndexGetArraySegment(t);\n if (void 0 === n) return null;\n for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, n.fieldPath)) switch (t.op) {\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n return t.value.arrayValue.values || [];\n\n case \"array-contains\" /* Operator.ARRAY_CONTAINS */ :\n return [ t.value ];\n // Remaining filters are not array filters.\n }\n return null;\n }\n /**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */ (s, i), _ = function __PRIVATE_targetGetNotInValues(e, t) {\n const n = new Map;\n for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(t)) for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, r.fieldPath)) switch (t.op) {\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n n.set(r.fieldPath.canonicalString(), t.value);\n break;\n\n case \"not-in\" /* Operator.NOT_IN */ :\n case \"!=\" /* Operator.NOT_EQUAL */ :\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n return n.set(r.fieldPath.canonicalString(), t.value), Array.from(n.values());\n // Remaining filters cannot be used as notIn bounds.\n }\n return null;\n }\n /**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */ (s, i), a = function __PRIVATE_targetGetLowerBound(e, t) {\n const n = [];\n let r = !0;\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) {\n const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.startAt) : __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.startAt);\n n.push(t.value), r && (r = t.inclusive);\n }\n return new Bound(n, r);\n }\n /**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */ (s, i), u = function __PRIVATE_targetGetUpperBound(e, t) {\n const n = [];\n let r = !0;\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) {\n const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.endAt) : __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.endAt);\n n.push(t.value), r && (r = t.inclusive);\n }\n return new Bound(n, r);\n }(s, i), c = this.hn(i, s, a), l = this.hn(i, s, u), h = this.Pn(i, s, _), P = this.In(i.indexId, o, c, a.inclusive, l, u.inclusive, h);\n return PersistencePromise.forEach(P, (i => n.j(i, t.limit).next((t => {\n t.forEach((t => {\n const n = DocumentKey.fromSegments(t.documentKey);\n e.has(n) || (e = e.add(n), r.push(n));\n }));\n }))));\n })).next((() => r));\n }\n return PersistencePromise.resolve(null);\n }));\n }\n cn(e) {\n let t = this.un.get(e);\n if (t) return t;\n if (0 === e.filters.length) t = [ e ]; else {\n t = __PRIVATE_getDnfTerms(CompositeFilter.create(e.filters, \"and\" /* CompositeOperator.AND */)).map((t => __PRIVATE_newTarget(e.path, e.collectionGroup, e.orderBy, t.getFilters(), e.limit, e.startAt, e.endAt)));\n }\n return this.un.set(e, t), t;\n }\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */ In(e, t, n, r, i, s, o) {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const _ = (null != t ? t.length : 1) * Math.max(n.length, i.length), a = _ / (null != t ? t.length : 1), u = [];\n for (let c = 0; c < _; ++c) {\n const _ = t ? this.Tn(t[c / a]) : Te, l = this.En(e, _, n[c % a], r), h = this.dn(e, _, i[c % a], s), P = o.map((t => this.En(e, _, t, \n /* inclusive= */ !0)));\n u.push(...this.createRange(l, h, P));\n }\n return u;\n }\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */ En(e, t, n, r) {\n const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);\n return r ? i : i.Jt();\n }\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */ dn(e, t, n, r) {\n const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);\n return r ? i.Jt() : i;\n }\n ln(e, t) {\n const n = new __PRIVATE_TargetIndexMatcher(t), r = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment();\n return this.getFieldIndexes(e, r).next((e => {\n // Return the index with the most number of segments.\n let t = null;\n for (const r of e) {\n n.tn(r) && (!t || r.fields.length > t.fields.length) && (t = r);\n }\n return t;\n }));\n }\n getIndexType(e, t) {\n let n = 2 /* IndexType.FULL */;\n const r = this.cn(t);\n return PersistencePromise.forEach(r, (t => this.ln(e, t).next((e => {\n e ? 0 /* IndexType.NONE */ !== n && e.fields.length < function __PRIVATE_targetGetSegmentCount(e) {\n let t = new SortedSet(FieldPath$1.comparator), n = !1;\n for (const r of e.filters) for (const e of r.getFlattenedFilters()) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n e.field.isKeyField() || (\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e.op ? n = !0 : t = t.add(e.field));\n for (const n of e.orderBy) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n n.field.isKeyField() || (t = t.add(n.field));\n return t.size + (n ? 1 : 0);\n }(t) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;\n })))).next((() => \n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n function __PRIVATE_targetHasLimit(e) {\n return null !== e.limit;\n }(t) && r.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));\n }\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */ An(e, t) {\n const n = new __PRIVATE_IndexByteEncoder;\n for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {\n const e = t.data.field(r.fieldPath);\n if (null == e) return null;\n const i = n.Ht(r.kind);\n __PRIVATE_FirestoreIndexValueWriter.bt.Pt(e, i);\n }\n return n.Wt();\n }\n /** Encodes a single value to the ascending index format. */ Tn(e) {\n const t = new __PRIVATE_IndexByteEncoder;\n return __PRIVATE_FirestoreIndexValueWriter.bt.Pt(e, t.Ht(0 /* IndexKind.ASCENDING */)), \n t.Wt();\n }\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */ Rn(e, t) {\n const n = new __PRIVATE_IndexByteEncoder;\n return __PRIVATE_FirestoreIndexValueWriter.bt.Pt(__PRIVATE_refValue(this.databaseId, t), n.Ht(function __PRIVATE_fieldIndexGetKeyOrder(e) {\n const t = __PRIVATE_fieldIndexGetDirectionalSegments(e);\n return 0 === t.length ? 0 /* IndexKind.ASCENDING */ : t[t.length - 1].kind;\n }(e))), n.Wt();\n }\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */ Pn(e, t, n) {\n if (null === n) return [];\n let r = [];\n r.push(new __PRIVATE_IndexByteEncoder);\n let i = 0;\n for (const s of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {\n const e = n[i++];\n for (const n of r) if (this.Vn(t, s.fieldPath) && isArray(e)) r = this.mn(r, s, e); else {\n const t = n.Ht(s.kind);\n __PRIVATE_FirestoreIndexValueWriter.bt.Pt(e, t);\n }\n }\n return this.fn(r);\n }\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */ hn(e, t, n) {\n return this.Pn(e, t, n.position);\n }\n /** Returns the byte representation for the provided encoders. */ fn(e) {\n const t = [];\n for (let n = 0; n < e.length; ++n) t[n] = e[n].Wt();\n return t;\n }\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */ mn(e, t, n) {\n const r = [ ...e ], i = [];\n for (const e of n.arrayValue.values || []) for (const n of r) {\n const r = new __PRIVATE_IndexByteEncoder;\n r.seed(n.Wt()), __PRIVATE_FirestoreIndexValueWriter.bt.Pt(e, r.Ht(t.kind)), i.push(r);\n }\n return i;\n }\n Vn(e, t) {\n return !!e.filters.find((e => e instanceof FieldFilter && e.field.isEqual(t) && (\"in\" /* Operator.IN */ === e.op || \"not-in\" /* Operator.NOT_IN */ === e.op)));\n }\n getFieldIndexes(e, t) {\n const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e);\n return (t ? n.W(\"collectionGroupIndex\", IDBKeyRange.bound(t, t)) : n.W()).next((e => {\n const t = [];\n return PersistencePromise.forEach(e, (e => r.get([ e.indexId, this.uid ]).next((n => {\n t.push(function __PRIVATE_fromDbIndexConfiguration(e, t) {\n const n = t ? new IndexState(t.sequenceNumber, new IndexOffset(__PRIVATE_fromDbTimestamp(t.readTime), new DocumentKey(__PRIVATE_decodeResourcePath(t.documentKey)), t.largestBatchId)) : IndexState.empty(), r = e.fields.map((([e, t]) => new IndexSegment(FieldPath$1.fromServerFormat(e), t)));\n return new FieldIndex(e.indexId, e.collectionGroup, r, n);\n }(e, n));\n })))).next((() => t));\n }));\n }\n getNextCollectionGroupToUpdate(e) {\n return this.getFieldIndexes(e).next((e => 0 === e.length ? null : (e.sort(((e, t) => {\n const n = e.indexState.sequenceNumber - t.indexState.sequenceNumber;\n return 0 !== n ? n : __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);\n })), e[0].collectionGroup)));\n }\n updateCollectionGroup(e, t, n) {\n const r = __PRIVATE_indexConfigurationStore(e), i = __PRIVATE_indexStateStore(e);\n return this.gn(e).next((e => r.W(\"collectionGroupIndex\", IDBKeyRange.bound(t, t)).next((t => PersistencePromise.forEach(t, (t => i.put(__PRIVATE_toDbIndexState(t.indexId, this.uid, e, n))))))));\n }\n updateIndexEntries(e, t) {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const n = new Map;\n return PersistencePromise.forEach(t, ((t, r) => {\n const i = n.get(t.collectionGroup);\n return (i ? PersistencePromise.resolve(i) : this.getFieldIndexes(e, t.collectionGroup)).next((i => (n.set(t.collectionGroup, i), \n PersistencePromise.forEach(i, (n => this.pn(e, t, n).next((t => {\n const i = this.yn(r, n);\n return t.isEqual(i) ? PersistencePromise.resolve() : this.wn(e, r, n, t, i);\n })))))));\n }));\n }\n Sn(e, t, n, r) {\n return __PRIVATE_indexEntriesStore(e).put({\n indexId: r.indexId,\n uid: this.uid,\n arrayValue: r.arrayValue,\n directionalValue: r.directionalValue,\n orderedDocumentKey: this.Rn(n, t.key),\n documentKey: t.key.path.toArray()\n });\n }\n bn(e, t, n, r) {\n return __PRIVATE_indexEntriesStore(e).delete([ r.indexId, this.uid, r.arrayValue, r.directionalValue, this.Rn(n, t.key), t.key.path.toArray() ]);\n }\n pn(e, t, n) {\n const r = __PRIVATE_indexEntriesStore(e);\n let i = new SortedSet(__PRIVATE_indexEntryComparator);\n return r.Y({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only([ n.indexId, this.uid, this.Rn(n, t) ])\n }, ((e, r) => {\n i = i.add(new __PRIVATE_IndexEntry(n.indexId, t, r.arrayValue, r.directionalValue));\n })).next((() => i));\n }\n /** Creates the index entries for the given document. */ yn(e, t) {\n let n = new SortedSet(__PRIVATE_indexEntryComparator);\n const r = this.An(t, e);\n if (null == r) return n;\n const i = __PRIVATE_fieldIndexGetArraySegment(t);\n if (null != i) {\n const s = e.data.field(i.fieldPath);\n if (isArray(s)) for (const i of s.arrayValue.values || []) n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, this.Tn(i), r));\n } else n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, Te, r));\n return n;\n }\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */ wn(e, t, n, r, i) {\n __PRIVATE_logDebug(\"IndexedDbIndexManager\", \"Updating index entries for document '%s'\", t.key);\n const s = [];\n return function __PRIVATE_diffSortedSets(e, t, n, r, i) {\n const s = e.getIterator(), o = t.getIterator();\n let _ = __PRIVATE_advanceIterator(s), a = __PRIVATE_advanceIterator(o);\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n for (;_ || a; ) {\n let e = !1, t = !1;\n if (_ && a) {\n const r = n(_, a);\n r < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n t = !0 : r > 0 && (\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n e = !0);\n } else null != _ ? t = !0 : e = !0;\n e ? (r(a), a = __PRIVATE_advanceIterator(o)) : t ? (i(_), _ = __PRIVATE_advanceIterator(s)) : (_ = __PRIVATE_advanceIterator(s), \n a = __PRIVATE_advanceIterator(o));\n }\n }(r, i, __PRIVATE_indexEntryComparator, (\n /* onAdd= */ r => {\n s.push(this.Sn(e, t, n, r));\n }), (\n /* onRemove= */ r => {\n s.push(this.bn(e, t, n, r));\n })), PersistencePromise.waitFor(s);\n }\n gn(e) {\n let t = 1;\n return __PRIVATE_indexStateStore(e).Y({\n index: \"sequenceNumberIndex\",\n reverse: !0,\n range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])\n }, ((e, n, r) => {\n r.done(), t = n.sequenceNumber + 1;\n })).next((() => t));\n }\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */ createRange(e, t, n) {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n n = n.sort(((e, t) => __PRIVATE_indexEntryComparator(e, t))).filter(((e, t, n) => !t || 0 !== __PRIVATE_indexEntryComparator(e, n[t - 1])));\n const r = [];\n r.push(e);\n for (const i of n) {\n const n = __PRIVATE_indexEntryComparator(i, e), s = __PRIVATE_indexEntryComparator(i, t);\n if (0 === n) \n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n r[0] = e.Jt(); else if (n > 0 && s < 0) \n // `notInValue` is in the middle of the range\n r.push(i), r.push(i.Jt()); else if (s > 0) \n // `notInValue` (and all following values) are out of the range\n break;\n }\n r.push(t);\n const i = [];\n for (let e = 0; e < r.length; e += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.Dn(r[e], r[e + 1])) return [];\n const t = [ r[e].indexId, this.uid, r[e].arrayValue, r[e].directionalValue, Te, [] ], n = [ r[e + 1].indexId, this.uid, r[e + 1].arrayValue, r[e + 1].directionalValue, Te, [] ];\n i.push(IDBKeyRange.bound(t, n));\n }\n return i;\n }\n Dn(e, t) {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return __PRIVATE_indexEntryComparator(e, t) > 0;\n }\n getMinOffsetFromCollectionGroup(e, t) {\n return this.getFieldIndexes(e, t).next(__PRIVATE_getMinOffsetFromFieldIndexes);\n }\n getMinOffset(e, t) {\n return PersistencePromise.mapArray(this.cn(t), (t => this.ln(e, t).next((e => e || fail())))).next(__PRIVATE_getMinOffsetFromFieldIndexes);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */ function __PRIVATE_collectionParentsStore(e) {\n return __PRIVATE_getStore(e, \"collectionParents\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */ function __PRIVATE_indexEntriesStore(e) {\n return __PRIVATE_getStore(e, \"indexEntries\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */ function __PRIVATE_indexConfigurationStore(e) {\n return __PRIVATE_getStore(e, \"indexConfiguration\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */ function __PRIVATE_indexStateStore(e) {\n return __PRIVATE_getStore(e, \"indexState\");\n}\n\nfunction __PRIVATE_getMinOffsetFromFieldIndexes(e) {\n __PRIVATE_hardAssert(0 !== e.length);\n let t = e[0].indexState.offset, n = t.largestBatchId;\n for (let r = 1; r < e.length; r++) {\n const i = e[r].indexState.offset;\n __PRIVATE_indexOffsetComparator(i, t) < 0 && (t = i), n < i.largestBatchId && (n = i.largestBatchId);\n }\n return new IndexOffset(t.readTime, t.documentKey, n);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ee = {\n didRun: !1,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nclass LruParams {\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n e, \n // The percentage of sequence numbers that we will attempt to collect\n t, \n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n n) {\n this.cacheSizeCollectionThreshold = e, this.percentileToCollect = t, this.maximumSequenceNumbersToCollect = n;\n }\n static withCacheSize(e) {\n return new LruParams(e, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nfunction removeMutationBatch(e, t, n) {\n const r = e.store(\"mutations\"), i = e.store(\"documentMutations\"), s = [], o = IDBKeyRange.only(n.batchId);\n let _ = 0;\n const a = r.Y({\n range: o\n }, ((e, t, n) => (_++, n.delete())));\n s.push(a.next((() => {\n __PRIVATE_hardAssert(1 === _);\n })));\n const u = [];\n for (const e of n.mutations) {\n const r = __PRIVATE_newDbDocumentMutationKey(t, e.key.path, n.batchId);\n s.push(i.delete(r)), u.push(e.key);\n }\n return PersistencePromise.waitFor(s).next((() => u));\n}\n\n/**\n * Returns an approximate size for the given document.\n */ function __PRIVATE_dbDocumentSize(e) {\n if (!e) return 0;\n let t;\n if (e.document) t = e.document; else if (e.unknownDocument) t = e.unknownDocument; else {\n if (!e.noDocument) throw fail();\n t = e.noDocument;\n }\n return JSON.stringify(t).length;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A mutation queue for a specific user, backed by IndexedDB. */ LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, \nLruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, LruParams.DEFAULT = new LruParams(41943040, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), \nLruParams.DISABLED = new LruParams(-1, 0, 0);\n\nclass __PRIVATE_IndexedDbMutationQueue {\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n e, t, n, r) {\n this.userId = e, this.serializer = t, this.indexManager = n, this.referenceDelegate = r, \n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n this.Cn = {};\n }\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */ static lt(e, t, n, r) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n __PRIVATE_hardAssert(\"\" !== e.uid);\n const i = e.isAuthenticated() ? e.uid : \"\";\n return new __PRIVATE_IndexedDbMutationQueue(i, t, n, r);\n }\n checkEmpty(e) {\n let t = !0;\n const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return __PRIVATE_mutationsStore(e).Y({\n index: \"userMutationsIndex\",\n range: n\n }, ((e, n, r) => {\n t = !1, r.done();\n })).next((() => t));\n }\n addMutationBatch(e, t, n, r) {\n const i = __PRIVATE_documentMutationsStore(e), s = __PRIVATE_mutationsStore(e);\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return s.add({}).next((o => {\n __PRIVATE_hardAssert(\"number\" == typeof o);\n const _ = new MutationBatch(o, t, n, r), a = function __PRIVATE_toDbMutationBatch(e, t, n) {\n const r = n.baseMutations.map((t => toMutation(e.ct, t))), i = n.mutations.map((t => toMutation(e.ct, t)));\n return {\n userId: t,\n batchId: n.batchId,\n localWriteTimeMs: n.localWriteTime.toMillis(),\n baseMutations: r,\n mutations: i\n };\n }(this.serializer, this.userId, _), u = [];\n let c = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString())));\n for (const e of r) {\n const t = __PRIVATE_newDbDocumentMutationKey(this.userId, e.key.path, o);\n c = c.add(e.key.path.popLast()), u.push(s.put(a)), u.push(i.put(t, x));\n }\n return c.forEach((t => {\n u.push(this.indexManager.addToCollectionParentIndex(e, t));\n })), e.addOnCommittedListener((() => {\n this.Cn[o] = _.keys();\n })), PersistencePromise.waitFor(u).next((() => _));\n }));\n }\n lookupMutationBatch(e, t) {\n return __PRIVATE_mutationsStore(e).get(t).next((e => e ? (__PRIVATE_hardAssert(e.userId === this.userId), \n __PRIVATE_fromDbMutationBatch(this.serializer, e)) : null));\n }\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n vn(e, t) {\n return this.Cn[t] ? PersistencePromise.resolve(this.Cn[t]) : this.lookupMutationBatch(e, t).next((e => {\n if (e) {\n const n = e.keys();\n return this.Cn[t] = n, n;\n }\n return null;\n }));\n }\n getNextMutationBatchAfterBatchId(e, t) {\n const n = t + 1, r = IDBKeyRange.lowerBound([ this.userId, n ]);\n let i = null;\n return __PRIVATE_mutationsStore(e).Y({\n index: \"userMutationsIndex\",\n range: r\n }, ((e, t, r) => {\n t.userId === this.userId && (__PRIVATE_hardAssert(t.batchId >= n), i = __PRIVATE_fromDbMutationBatch(this.serializer, t)), \n r.done();\n })).next((() => i));\n }\n getHighestUnacknowledgedBatchId(e) {\n const t = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);\n let n = -1;\n return __PRIVATE_mutationsStore(e).Y({\n index: \"userMutationsIndex\",\n range: t,\n reverse: !0\n }, ((e, t, r) => {\n n = t.batchId, r.done();\n })).next((() => n));\n }\n getAllMutationBatches(e) {\n const t = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return __PRIVATE_mutationsStore(e).W(\"userMutationsIndex\", t).next((e => e.map((e => __PRIVATE_fromDbMutationBatch(this.serializer, e)))));\n }\n getAllMutationBatchesAffectingDocumentKey(e, t) {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const n = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), r = IDBKeyRange.lowerBound(n), i = [];\n return __PRIVATE_documentMutationsStore(e).Y({\n range: r\n }, ((n, r, s) => {\n const [o, _, a] = n, u = __PRIVATE_decodeResourcePath(_);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n if (o === this.userId && t.path.isEqual(u)) \n // Look up the mutation batch in the store.\n return __PRIVATE_mutationsStore(e).get(a).next((e => {\n if (!e) throw fail();\n __PRIVATE_hardAssert(e.userId === this.userId), i.push(__PRIVATE_fromDbMutationBatch(this.serializer, e));\n }));\n s.done();\n })).next((() => i));\n }\n getAllMutationBatchesAffectingDocumentKeys(e, t) {\n let n = new SortedSet(__PRIVATE_primitiveComparator);\n const r = [];\n return t.forEach((t => {\n const i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), s = IDBKeyRange.lowerBound(i), o = __PRIVATE_documentMutationsStore(e).Y({\n range: s\n }, ((e, r, i) => {\n const [s, o, _] = e, a = __PRIVATE_decodeResourcePath(o);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n s === this.userId && t.path.isEqual(a) ? n = n.add(_) : i.done();\n }));\n r.push(o);\n })), PersistencePromise.waitFor(r).next((() => this.Fn(e, n)));\n }\n getAllMutationBatchesAffectingQuery(e, t) {\n const n = t.path, r = n.length + 1, i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n), s = IDBKeyRange.lowerBound(i);\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let o = new SortedSet(__PRIVATE_primitiveComparator);\n return __PRIVATE_documentMutationsStore(e).Y({\n range: s\n }, ((e, t, i) => {\n const [s, _, a] = e, u = __PRIVATE_decodeResourcePath(_);\n s === this.userId && n.isPrefixOf(u) ? \n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n u.length === r && (o = o.add(a)) : i.done();\n })).next((() => this.Fn(e, o)));\n }\n Fn(e, t) {\n const n = [], r = [];\n // TODO(rockwood): Implement this using iterate.\n return t.forEach((t => {\n r.push(__PRIVATE_mutationsStore(e).get(t).next((e => {\n if (null === e) throw fail();\n __PRIVATE_hardAssert(e.userId === this.userId), n.push(__PRIVATE_fromDbMutationBatch(this.serializer, e));\n })));\n })), PersistencePromise.waitFor(r).next((() => n));\n }\n removeMutationBatch(e, t) {\n return removeMutationBatch(e.ae, this.userId, t).next((n => (e.addOnCommittedListener((() => {\n this.Mn(t.batchId);\n })), PersistencePromise.forEach(n, (t => this.referenceDelegate.markPotentiallyOrphaned(e, t))))));\n }\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n Mn(e) {\n delete this.Cn[e];\n }\n performConsistencyCheck(e) {\n return this.checkEmpty(e).next((t => {\n if (!t) return PersistencePromise.resolve();\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const n = IDBKeyRange.lowerBound(\n /**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\n function __PRIVATE_newDbDocumentMutationPrefixForUser(e) {\n return [ e ];\n }(this.userId)), r = [];\n return __PRIVATE_documentMutationsStore(e).Y({\n range: n\n }, ((e, t, n) => {\n if (e[0] === this.userId) {\n const t = __PRIVATE_decodeResourcePath(e[1]);\n r.push(t);\n } else n.done();\n })).next((() => {\n __PRIVATE_hardAssert(0 === r.length);\n }));\n }));\n }\n containsKey(e, t) {\n return __PRIVATE_mutationQueueContainsKey(e, this.userId, t);\n }\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n xn(e) {\n return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e => e || {\n userId: this.userId,\n lastAcknowledgedBatchId: -1,\n lastStreamToken: \"\"\n }));\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */ function __PRIVATE_mutationQueueContainsKey(e, t, n) {\n const r = __PRIVATE_newDbDocumentMutationPrefixForPath(t, n.path), i = r[1], s = IDBKeyRange.lowerBound(r);\n let o = !1;\n return __PRIVATE_documentMutationsStore(e).Y({\n range: s,\n J: !0\n }, ((e, n, r) => {\n const [s, _, /*batchID*/ a] = e;\n s === t && _ === i && (o = !0), r.done();\n })).next((() => o));\n}\n\n/** Returns true if any mutation queue contains the given document. */\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction __PRIVATE_mutationsStore(e) {\n return __PRIVATE_getStore(e, \"mutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function __PRIVATE_documentMutationsStore(e) {\n return __PRIVATE_getStore(e, \"documentMutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function __PRIVATE_mutationQueuesStore(e) {\n return __PRIVATE_getStore(e, \"mutationQueues\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Offset to ensure non-overlapping target ids. */\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nclass __PRIVATE_TargetIdGenerator {\n constructor(e) {\n this.On = e;\n }\n next() {\n return this.On += 2, this.On;\n }\n static Nn() {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new __PRIVATE_TargetIdGenerator(0);\n }\n static Ln() {\n // Sync engine assigns target IDs for limbo document detection.\n return new __PRIVATE_TargetIdGenerator(-1);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_IndexedDbTargetCache {\n constructor(e, t) {\n this.referenceDelegate = e, this.serializer = t;\n }\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n allocateTargetId(e) {\n return this.Bn(e).next((t => {\n const n = new __PRIVATE_TargetIdGenerator(t.highestTargetId);\n return t.highestTargetId = n.next(), this.kn(e, t).next((() => t.highestTargetId));\n }));\n }\n getLastRemoteSnapshotVersion(e) {\n return this.Bn(e).next((e => SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds, e.lastRemoteSnapshotVersion.nanoseconds))));\n }\n getHighestSequenceNumber(e) {\n return this.Bn(e).next((e => e.highestListenSequenceNumber));\n }\n setTargetsMetadata(e, t, n) {\n return this.Bn(e).next((r => (r.highestListenSequenceNumber = t, n && (r.lastRemoteSnapshotVersion = n.toTimestamp()), \n t > r.highestListenSequenceNumber && (r.highestListenSequenceNumber = t), this.kn(e, r))));\n }\n addTargetData(e, t) {\n return this.qn(e, t).next((() => this.Bn(e).next((n => (n.targetCount += 1, this.Qn(t, n), \n this.kn(e, n))))));\n }\n updateTargetData(e, t) {\n return this.qn(e, t);\n }\n removeTargetData(e, t) {\n return this.removeMatchingKeysForTargetId(e, t.targetId).next((() => __PRIVATE_targetsStore(e).delete(t.targetId))).next((() => this.Bn(e))).next((t => (__PRIVATE_hardAssert(t.targetCount > 0), \n t.targetCount -= 1, this.kn(e, t))));\n }\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */ removeTargets(e, t, n) {\n let r = 0;\n const i = [];\n return __PRIVATE_targetsStore(e).Y(((s, o) => {\n const _ = __PRIVATE_fromDbTarget(o);\n _.sequenceNumber <= t && null === n.get(_.targetId) && (r++, i.push(this.removeTargetData(e, _)));\n })).next((() => PersistencePromise.waitFor(i))).next((() => r));\n }\n /**\n * Call provided function with each `TargetData` that we have cached.\n */ forEachTarget(e, t) {\n return __PRIVATE_targetsStore(e).Y(((e, n) => {\n const r = __PRIVATE_fromDbTarget(n);\n t(r);\n }));\n }\n Bn(e) {\n return __PRIVATE_globalTargetStore(e).get(\"targetGlobalKey\").next((e => (__PRIVATE_hardAssert(null !== e), \n e)));\n }\n kn(e, t) {\n return __PRIVATE_globalTargetStore(e).put(\"targetGlobalKey\", t);\n }\n qn(e, t) {\n return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer, t));\n }\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */ Qn(e, t) {\n let n = !1;\n return e.targetId > t.highestTargetId && (t.highestTargetId = e.targetId, n = !0), \n e.sequenceNumber > t.highestListenSequenceNumber && (t.highestListenSequenceNumber = e.sequenceNumber, \n n = !0), n;\n }\n getTargetCount(e) {\n return this.Bn(e).next((e => e.targetCount));\n }\n getTargetData(e, t) {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const n = __PRIVATE_canonifyTarget(t), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);\n let i = null;\n return __PRIVATE_targetsStore(e).Y({\n range: r,\n index: \"queryTargetsIndex\"\n }, ((e, n, r) => {\n const s = __PRIVATE_fromDbTarget(n);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n __PRIVATE_targetEquals(t, s.target) && (i = s, r.done());\n })).next((() => i));\n }\n addMatchingKeys(e, t, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const r = [], i = __PRIVATE_documentTargetStore(e);\n return t.forEach((t => {\n const s = __PRIVATE_encodeResourcePath(t.path);\n r.push(i.put({\n targetId: n,\n path: s\n })), r.push(this.referenceDelegate.addReference(e, n, t));\n })), PersistencePromise.waitFor(r);\n }\n removeMatchingKeys(e, t, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const r = __PRIVATE_documentTargetStore(e);\n return PersistencePromise.forEach(t, (t => {\n const i = __PRIVATE_encodeResourcePath(t.path);\n return PersistencePromise.waitFor([ r.delete([ n, i ]), this.referenceDelegate.removeReference(e, n, t) ]);\n }));\n }\n removeMatchingKeysForTargetId(e, t) {\n const n = __PRIVATE_documentTargetStore(e), r = IDBKeyRange.bound([ t ], [ t + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return n.delete(r);\n }\n getMatchingKeysForTargetId(e, t) {\n const n = IDBKeyRange.bound([ t ], [ t + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0), r = __PRIVATE_documentTargetStore(e);\n let i = __PRIVATE_documentKeySet();\n return r.Y({\n range: n,\n J: !0\n }, ((e, t, n) => {\n const r = __PRIVATE_decodeResourcePath(e[1]), s = new DocumentKey(r);\n i = i.add(s);\n })).next((() => i));\n }\n containsKey(e, t) {\n const n = __PRIVATE_encodeResourcePath(t.path), r = IDBKeyRange.bound([ n ], [ __PRIVATE_immediateSuccessor(n) ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n let i = 0;\n return __PRIVATE_documentTargetStore(e).Y({\n index: \"documentTargetsIndex\",\n J: !0,\n range: r\n }, (([e, t], n, r) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n 0 !== e && (i++, r.done());\n })).next((() => i > 0));\n }\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n _t(e, t) {\n return __PRIVATE_targetsStore(e).get(t).next((e => e ? __PRIVATE_fromDbTarget(e) : null));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */ function __PRIVATE_targetsStore(e) {\n return __PRIVATE_getStore(e, \"targets\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */ function __PRIVATE_globalTargetStore(e) {\n return __PRIVATE_getStore(e, \"targetGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */ function __PRIVATE_documentTargetStore(e) {\n return __PRIVATE_getStore(e, \"targetDocuments\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_bufferEntryComparator([e, t], [n, r]) {\n const i = __PRIVATE_primitiveComparator(e, n);\n return 0 === i ? __PRIVATE_primitiveComparator(t, r) : i;\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */ class __PRIVATE_RollingSequenceNumberBuffer {\n constructor(e) {\n this.Kn = e, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.$n = 0;\n }\n Un() {\n return ++this.$n;\n }\n Wn(e) {\n const t = [ e, this.Un() ];\n if (this.buffer.size < this.Kn) this.buffer = this.buffer.add(t); else {\n const e = this.buffer.last();\n __PRIVATE_bufferEntryComparator(t, e) < 0 && (this.buffer = this.buffer.delete(e).add(t));\n }\n }\n get maxValue() {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()[0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */ class __PRIVATE_LruScheduler {\n constructor(e, t, n) {\n this.garbageCollector = e, this.asyncQueue = t, this.localStore = n, this.Gn = null;\n }\n start() {\n -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.zn(6e4);\n }\n stop() {\n this.Gn && (this.Gn.cancel(), this.Gn = null);\n }\n get started() {\n return null !== this.Gn;\n }\n zn(e) {\n __PRIVATE_logDebug(\"LruGarbageCollector\", `Garbage collection scheduled in ${e}ms`), \n this.Gn = this.asyncQueue.enqueueAfterDelay(\"lru_garbage_collection\" /* TimerId.LruGarbageCollection */ , e, (async () => {\n this.Gn = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(\"LruGarbageCollector\", \"Ignoring IndexedDB error during garbage collection: \", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n }\n await this.zn(3e5);\n }));\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */ class __PRIVATE_LruGarbageCollectorImpl {\n constructor(e, t) {\n this.jn = e, this.params = t;\n }\n calculateTargetCount(e, t) {\n return this.jn.Hn(e).next((e => Math.floor(t / 100 * e)));\n }\n nthSequenceNumber(e, t) {\n if (0 === t) return PersistencePromise.resolve(__PRIVATE_ListenSequence._e);\n const n = new __PRIVATE_RollingSequenceNumberBuffer(t);\n return this.jn.forEachTarget(e, (e => n.Wn(e.sequenceNumber))).next((() => this.jn.Jn(e, (e => n.Wn(e))))).next((() => n.maxValue));\n }\n removeTargets(e, t, n) {\n return this.jn.removeTargets(e, t, n);\n }\n removeOrphanedDocuments(e, t) {\n return this.jn.removeOrphanedDocuments(e, t);\n }\n collect(e, t) {\n return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug(\"LruGarbageCollector\", \"Garbage collection skipped; disabled\"), \n PersistencePromise.resolve(Ee)) : this.getCacheSize(e).next((n => n < this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug(\"LruGarbageCollector\", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), \n Ee) : this.Yn(e, t)));\n }\n getCacheSize(e) {\n return this.jn.getCacheSize(e);\n }\n Yn(e, t) {\n let n, r, i, s, o, a, u;\n const c = Date.now();\n return this.calculateTargetCount(e, this.params.percentileToCollect).next((t => (\n // Cap at the configured max\n t > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug(\"LruGarbageCollector\", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`), \n r = this.params.maximumSequenceNumbersToCollect) : r = t, s = Date.now(), this.nthSequenceNumber(e, r)))).next((r => (n = r, \n o = Date.now(), this.removeTargets(e, n, t)))).next((t => (i = t, a = Date.now(), \n this.removeOrphanedDocuments(e, n)))).next((e => {\n if (u = Date.now(), __PRIVATE_getLogLevel() <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.DEBUG) {\n __PRIVATE_logDebug(\"LruGarbageCollector\", `LRU Garbage Collection\\n\\tCounted targets in ${s - c}ms\\n\\tDetermined least recently used ${r} in ` + (o - s) + \"ms\\n\" + `\\tRemoved ${i} targets in ` + (a - o) + \"ms\\n\" + `\\tRemoved ${e} documents in ` + (u - a) + \"ms\\n\" + `Total Duration: ${u - c}ms`);\n }\n return PersistencePromise.resolve({\n didRun: !0,\n sequenceNumbersCollected: r,\n targetsRemoved: i,\n documentsRemoved: e\n });\n }));\n }\n}\n\nfunction __PRIVATE_newLruGarbageCollector(e, t) {\n return new __PRIVATE_LruGarbageCollectorImpl(e, t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Provides LRU functionality for IndexedDB persistence. */ class __PRIVATE_IndexedDbLruDelegateImpl {\n constructor(e, t) {\n this.db = e, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);\n }\n Hn(e) {\n const t = this.Zn(e);\n return this.db.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t))));\n }\n Zn(e) {\n let t = 0;\n return this.Jn(e, (e => {\n t++;\n })).next((() => t));\n }\n forEachTarget(e, t) {\n return this.db.getTargetCache().forEachTarget(e, t);\n }\n Jn(e, t) {\n return this.Xn(e, ((e, n) => t(n)));\n }\n addReference(e, t, n) {\n return __PRIVATE_writeSentinelKey(e, n);\n }\n removeReference(e, t, n) {\n return __PRIVATE_writeSentinelKey(e, n);\n }\n removeTargets(e, t, n) {\n return this.db.getTargetCache().removeTargets(e, t, n);\n }\n markPotentiallyOrphaned(e, t) {\n return __PRIVATE_writeSentinelKey(e, t);\n }\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */ er(e, t) {\n return function __PRIVATE_mutationQueuesContainKey(e, t) {\n let n = !1;\n return __PRIVATE_mutationQueuesStore(e).Z((r => __PRIVATE_mutationQueueContainsKey(e, r, t).next((e => (e && (n = !0), \n PersistencePromise.resolve(!e)))))).next((() => n));\n }(e, t);\n }\n removeOrphanedDocuments(e, t) {\n const n = this.db.getRemoteDocumentCache().newChangeBuffer(), r = [];\n let i = 0;\n return this.Xn(e, ((s, o) => {\n if (o <= t) {\n const t = this.er(e, s).next((t => {\n if (!t) \n // Our size accounting requires us to read all documents before\n // removing them.\n return i++, n.getEntry(e, s).next((() => (n.removeEntry(s, SnapshotVersion.min()), \n __PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e) {\n return [ 0, __PRIVATE_encodeResourcePath(e.path) ];\n }\n /**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */ (s)))));\n }));\n r.push(t);\n }\n })).next((() => PersistencePromise.waitFor(r))).next((() => n.apply(e))).next((() => i));\n }\n removeTarget(e, t) {\n const n = t.withSequenceNumber(e.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(e, n);\n }\n updateLimboDocument(e, t) {\n return __PRIVATE_writeSentinelKey(e, t);\n }\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */ Xn(e, t) {\n const n = __PRIVATE_documentTargetStore(e);\n let r, i = __PRIVATE_ListenSequence._e;\n return n.Y({\n index: \"documentTargetsIndex\"\n }, (([e, n], {path: s, sequenceNumber: o}) => {\n 0 === e ? (\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n i !== __PRIVATE_ListenSequence._e && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i), \n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n i = o, r = s) : \n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n i = __PRIVATE_ListenSequence._e;\n })).next((() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n i !== __PRIVATE_ListenSequence._e && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i);\n }));\n }\n getCacheSize(e) {\n return this.db.getRemoteDocumentCache().getSize(e);\n }\n}\n\nfunction __PRIVATE_writeSentinelKey(e, t) {\n return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e, t) {\n return {\n targetId: 0,\n path: __PRIVATE_encodeResourcePath(e.path),\n sequenceNumber: t\n };\n }(t, e.currentSequenceNumber));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */ class RemoteDocumentChangeBuffer {\n constructor() {\n // A mapping of document key to the new cache entry that should be written.\n this.changes = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))), this.changesApplied = !1;\n }\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ addEntry(e) {\n this.assertNotApplied(), this.changes.set(e.key, e);\n }\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ removeEntry(e, t) {\n this.assertNotApplied(), this.changes.set(e, MutableDocument.newInvalidDocument(e).setReadTime(t));\n }\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */ getEntry(e, t) {\n this.assertNotApplied();\n const n = this.changes.get(t);\n return void 0 !== n ? PersistencePromise.resolve(n) : this.getFromCache(e, t);\n }\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */ getEntries(e, t) {\n return this.getAllFromCache(e, t);\n }\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */ apply(e) {\n return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(e);\n }\n /** Helper to assert this.changes is not null */ assertNotApplied() {}\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */ class __PRIVATE_IndexedDbRemoteDocumentCacheImpl {\n constructor(e) {\n this.serializer = e;\n }\n setIndexManager(e) {\n this.indexManager = e;\n }\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ addEntry(e, t, n) {\n return __PRIVATE_remoteDocumentsStore(e).put(n);\n }\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ removeEntry(e, t, n) {\n return __PRIVATE_remoteDocumentsStore(e).delete(\n /**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\n function __PRIVATE_dbReadTimeKey(e, t) {\n const n = e.path.toArray();\n return [ \n /* prefix path */ n.slice(0, n.length - 2), \n /* collection id */ n[n.length - 2], __PRIVATE_toDbTimestampKey(t), \n /* document id */ n[n.length - 1] ];\n }\n /**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */ (t, n));\n }\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */ updateMetadata(e, t) {\n return this.getMetadata(e).next((n => (n.byteSize += t, this.tr(e, n))));\n }\n getEntry(e, t) {\n let n = MutableDocument.newInvalidDocument(t);\n return __PRIVATE_remoteDocumentsStore(e).Y({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(__PRIVATE_dbKey(t))\n }, ((e, r) => {\n n = this.nr(t, r);\n })).next((() => n));\n }\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */ rr(e, t) {\n let n = {\n size: 0,\n document: MutableDocument.newInvalidDocument(t)\n };\n return __PRIVATE_remoteDocumentsStore(e).Y({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(__PRIVATE_dbKey(t))\n }, ((e, r) => {\n n = {\n document: this.nr(t, r),\n size: __PRIVATE_dbDocumentSize(r)\n };\n })).next((() => n));\n }\n getEntries(e, t) {\n let n = __PRIVATE_mutableDocumentMap();\n return this.ir(e, t, ((e, t) => {\n const r = this.nr(e, t);\n n = n.insert(e, r);\n })).next((() => n));\n }\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */ sr(e, t) {\n let n = __PRIVATE_mutableDocumentMap(), r = new SortedMap(DocumentKey.comparator);\n return this.ir(e, t, ((e, t) => {\n const i = this.nr(e, t);\n n = n.insert(e, i), r = r.insert(e, __PRIVATE_dbDocumentSize(t));\n })).next((() => ({\n documents: n,\n _r: r\n })));\n }\n ir(e, t, n) {\n if (t.isEmpty()) return PersistencePromise.resolve();\n let r = new SortedSet(__PRIVATE_dbKeyComparator);\n t.forEach((e => r = r.add(e)));\n const i = IDBKeyRange.bound(__PRIVATE_dbKey(r.first()), __PRIVATE_dbKey(r.last())), s = r.getIterator();\n let o = s.getNext();\n return __PRIVATE_remoteDocumentsStore(e).Y({\n index: \"documentKeyIndex\",\n range: i\n }, ((e, t, r) => {\n const i = DocumentKey.fromSegments([ ...t.prefixPath, t.collectionGroup, t.documentId ]);\n // Go through keys not found in cache.\n for (;o && __PRIVATE_dbKeyComparator(o, i) < 0; ) n(o, null), o = s.getNext();\n o && o.isEqual(i) && (\n // Key found in cache.\n n(o, t), o = s.hasNext() ? s.getNext() : null), \n // Skip to the next key (if there is one).\n o ? r.U(__PRIVATE_dbKey(o)) : r.done();\n })).next((() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n for (;o; ) n(o, null), o = s.hasNext() ? s.getNext() : null;\n }));\n }\n getDocumentsMatchingQuery(e, t, n, r, i) {\n const s = t.path, o = [ s.popLast().toArray(), s.lastSegment(), __PRIVATE_toDbTimestampKey(n.readTime), n.documentKey.path.isEmpty() ? \"\" : n.documentKey.path.lastSegment() ], _ = [ s.popLast().toArray(), s.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], \"\" ];\n return __PRIVATE_remoteDocumentsStore(e).W(IDBKeyRange.bound(o, _, !0)).next((e => {\n null == i || i.incrementDocumentReadCount(e.length);\n let n = __PRIVATE_mutableDocumentMap();\n for (const i of e) {\n const e = this.nr(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i);\n e.isFoundDocument() && (__PRIVATE_queryMatches(t, e) || r.has(e.key)) && (\n // Either the document matches the given query, or it is mutated.\n n = n.insert(e.key, e));\n }\n return n;\n }));\n }\n getAllFromCollectionGroup(e, t, n, r) {\n let i = __PRIVATE_mutableDocumentMap();\n const s = __PRIVATE_dbCollectionGroupKey(t, n), o = __PRIVATE_dbCollectionGroupKey(t, IndexOffset.max());\n return __PRIVATE_remoteDocumentsStore(e).Y({\n index: \"collectionGroupIndex\",\n range: IDBKeyRange.bound(s, o, !0)\n }, ((e, t, n) => {\n const s = this.nr(DocumentKey.fromSegments(t.prefixPath.concat(t.collectionGroup, t.documentId)), t);\n i = i.insert(s.key, s), i.size === r && n.done();\n })).next((() => i));\n }\n newChangeBuffer(e) {\n return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e && e.trackRemovals);\n }\n getSize(e) {\n return this.getMetadata(e).next((e => e.byteSize));\n }\n getMetadata(e) {\n return __PRIVATE_documentGlobalStore(e).get(\"remoteDocumentGlobalKey\").next((e => (__PRIVATE_hardAssert(!!e), \n e)));\n }\n tr(e, t) {\n return __PRIVATE_documentGlobalStore(e).put(\"remoteDocumentGlobalKey\", t);\n }\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */ nr(e, t) {\n if (t) {\n const e = __PRIVATE_fromDbRemoteDocument(this.serializer, t);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n if (!(e.isNoDocument() && e.version.isEqual(SnapshotVersion.min()))) return e;\n }\n return MutableDocument.newInvalidDocument(e);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */ function __PRIVATE_newIndexedDbRemoteDocumentCache(e) {\n return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */ class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(e, t) {\n super(), this.ar = e, this.trackRemovals = t, \n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n this.ur = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t)));\n }\n applyChanges(e) {\n const t = [];\n let n = 0, r = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString())));\n return this.changes.forEach(((i, s) => {\n const o = this.ur.get(i);\n if (t.push(this.ar.removeEntry(e, i, o.readTime)), s.isValidDocument()) {\n const _ = __PRIVATE_toDbRemoteDocument(this.ar.serializer, s);\n r = r.add(i.path.popLast());\n const a = __PRIVATE_dbDocumentSize(_);\n n += a - o.size, t.push(this.ar.addEntry(e, i, _));\n } else if (n -= o.size, this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const n = __PRIVATE_toDbRemoteDocument(this.ar.serializer, s.convertToNoDocument(SnapshotVersion.min()));\n t.push(this.ar.addEntry(e, i, n));\n }\n })), r.forEach((n => {\n t.push(this.ar.indexManager.addToCollectionParentIndex(e, n));\n })), t.push(this.ar.updateMetadata(e, n)), PersistencePromise.waitFor(t);\n }\n getFromCache(e, t) {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.ar.rr(e, t).next((e => (this.ur.set(t, {\n size: e.size,\n readTime: e.document.readTime\n }), e.document)));\n }\n getAllFromCache(e, t) {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.ar.sr(e, t).next((({documents: e, _r: t}) => (\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n t.forEach(((t, n) => {\n this.ur.set(t, {\n size: n,\n readTime: e.get(t).readTime\n });\n })), e)));\n }\n}\n\nfunction __PRIVATE_documentGlobalStore(e) {\n return __PRIVATE_getStore(e, \"remoteDocumentGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */ function __PRIVATE_remoteDocumentsStore(e) {\n return __PRIVATE_getStore(e, \"remoteDocumentsV14\");\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */ function __PRIVATE_dbKey(e) {\n const t = e.path.toArray();\n return [ \n /* prefix path */ t.slice(0, t.length - 2), \n /* collection id */ t[t.length - 2], \n /* document id */ t[t.length - 1] ];\n}\n\nfunction __PRIVATE_dbCollectionGroupKey(e, t) {\n const n = t.documentKey.path.toArray();\n return [ \n /* collection id */ e, __PRIVATE_toDbTimestampKey(t.readTime), \n /* prefix path */ n.slice(0, n.length - 2), \n /* document id */ n.length > 0 ? n[n.length - 1] : \"\" ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */ function __PRIVATE_dbKeyComparator(e, t) {\n const n = e.path.toArray(), r = t.path.toArray();\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let i = 0;\n for (let e = 0; e < n.length - 2 && e < r.length - 2; ++e) if (i = __PRIVATE_primitiveComparator(n[e], r[e]), \n i) return i;\n return i = __PRIVATE_primitiveComparator(n.length, r.length), i || (i = __PRIVATE_primitiveComparator(n[n.length - 2], r[r.length - 2]), \n i || __PRIVATE_primitiveComparator(n[n.length - 1], r[r.length - 1]));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nclass OverlayedDocument {\n constructor(e, \n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n t) {\n this.overlayedDocument = e, this.mutatedFields = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */ class LocalDocumentsView {\n constructor(e, t, n, r) {\n this.remoteDocumentCache = e, this.mutationQueue = t, this.documentOverlayCache = n, \n this.indexManager = r;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */ getDocument(e, t) {\n let n = null;\n return this.documentOverlayCache.getOverlay(e, t).next((r => (n = r, this.remoteDocumentCache.getEntry(e, t)))).next((e => (null !== n && __PRIVATE_mutationApplyToLocalView(n.mutation, e, FieldMask.empty(), Timestamp.now()), \n e)));\n }\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */ getDocuments(e, t) {\n return this.remoteDocumentCache.getEntries(e, t).next((t => this.getLocalViewOfDocuments(e, t, __PRIVATE_documentKeySet()).next((() => t))));\n }\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */ getLocalViewOfDocuments(e, t, n = __PRIVATE_documentKeySet()) {\n const r = __PRIVATE_newOverlayMap();\n return this.populateOverlays(e, r, t).next((() => this.computeViews(e, t, r, n).next((e => {\n let t = documentMap();\n return e.forEach(((e, n) => {\n t = t.insert(e, n.overlayedDocument);\n })), t;\n }))));\n }\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */ getOverlayedDocuments(e, t) {\n const n = __PRIVATE_newOverlayMap();\n return this.populateOverlays(e, n, t).next((() => this.computeViews(e, t, n, __PRIVATE_documentKeySet())));\n }\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */ populateOverlays(e, t, n) {\n const r = [];\n return n.forEach((e => {\n t.has(e) || r.push(e);\n })), this.documentOverlayCache.getOverlays(e, r).next((e => {\n e.forEach(((e, n) => {\n t.set(e, n);\n }));\n }));\n }\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */ computeViews(e, t, n, r) {\n let i = __PRIVATE_mutableDocumentMap();\n const s = __PRIVATE_newDocumentKeyMap(), o = function __PRIVATE_newOverlayedDocumentMap() {\n return __PRIVATE_newDocumentKeyMap();\n }();\n return t.forEach(((e, t) => {\n const o = n.get(t.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n r.has(t.key) && (void 0 === o || o.mutation instanceof __PRIVATE_PatchMutation) ? i = i.insert(t.key, t) : void 0 !== o ? (s.set(t.key, o.mutation.getFieldMask()), \n __PRIVATE_mutationApplyToLocalView(o.mutation, t, o.mutation.getFieldMask(), Timestamp.now())) : \n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n s.set(t.key, FieldMask.empty());\n })), this.recalculateAndSaveOverlays(e, i).next((e => (e.forEach(((e, t) => s.set(e, t))), \n t.forEach(((e, t) => {\n var n;\n return o.set(e, new OverlayedDocument(t, null !== (n = s.get(e)) && void 0 !== n ? n : null));\n })), o)));\n }\n recalculateAndSaveOverlays(e, t) {\n const n = __PRIVATE_newDocumentKeyMap();\n // A reverse lookup map from batch id to the documents within that batch.\n let r = new SortedMap(((e, t) => e - t)), i = __PRIVATE_documentKeySet();\n return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e, t).next((e => {\n for (const i of e) i.keys().forEach((e => {\n const s = t.get(e);\n if (null === s) return;\n let o = n.get(e) || FieldMask.empty();\n o = i.applyToLocalView(s, o), n.set(e, o);\n const _ = (r.get(i.batchId) || __PRIVATE_documentKeySet()).add(e);\n r = r.insert(i.batchId, _);\n }));\n })).next((() => {\n const s = [], o = r.getReverseIterator();\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n for (;o.hasNext(); ) {\n const r = o.getNext(), _ = r.key, a = r.value, u = __PRIVATE_newMutationMap();\n a.forEach((e => {\n if (!i.has(e)) {\n const r = __PRIVATE_calculateOverlayMutation(t.get(e), n.get(e));\n null !== r && u.set(e, r), i = i.add(e);\n }\n })), s.push(this.documentOverlayCache.saveOverlays(e, _, u));\n }\n return PersistencePromise.waitFor(s);\n })).next((() => n));\n }\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */ recalculateAndSaveOverlaysForDocumentKeys(e, t) {\n return this.remoteDocumentCache.getEntries(e, t).next((t => this.recalculateAndSaveOverlays(e, t)));\n }\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n * @param context - A optional tracker to keep a record of important details\n * during database local query execution.\n */ getDocumentsMatchingQuery(e, t, n, r) {\n /**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\n return function __PRIVATE_isDocumentQuery$1(e) {\n return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;\n }(t) ? this.getDocumentsMatchingDocumentQuery(e, t.path) : __PRIVATE_isCollectionGroupQuery(t) ? this.getDocumentsMatchingCollectionGroupQuery(e, t, n, r) : this.getDocumentsMatchingCollectionQuery(e, t, n, r);\n }\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n *
The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */ getNextDocuments(e, t, n, r) {\n return this.remoteDocumentCache.getAllFromCollectionGroup(e, t, n, r).next((i => {\n const s = r - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e, t, n.largestBatchId, r - i.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let o = -1, _ = i;\n return s.next((t => PersistencePromise.forEach(t, ((t, n) => (o < n.largestBatchId && (o = n.largestBatchId), \n i.get(t) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e, t).next((e => {\n _ = _.insert(t, e);\n }))))).next((() => this.populateOverlays(e, t, i))).next((() => this.computeViews(e, _, t, __PRIVATE_documentKeySet()))).next((e => ({\n batchId: o,\n changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e)\n })))));\n }));\n }\n getDocumentsMatchingDocumentQuery(e, t) {\n // Just do a simple document lookup.\n return this.getDocument(e, new DocumentKey(t)).next((e => {\n let t = documentMap();\n return e.isFoundDocument() && (t = t.insert(e.key, e)), t;\n }));\n }\n getDocumentsMatchingCollectionGroupQuery(e, t, n, r) {\n const i = t.collectionGroup;\n let s = documentMap();\n return this.indexManager.getCollectionParents(e, i).next((o => PersistencePromise.forEach(o, (o => {\n const _ = function __PRIVATE_asCollectionQueryAtPath(e, t) {\n return new __PRIVATE_QueryImpl(t, \n /*collectionGroup=*/ null, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);\n }(t, o.child(i));\n return this.getDocumentsMatchingCollectionQuery(e, _, n, r).next((e => {\n e.forEach(((e, t) => {\n s = s.insert(e, t);\n }));\n }));\n })).next((() => s))));\n }\n getDocumentsMatchingCollectionQuery(e, t, n, r) {\n // Query the remote documents and overlay mutations.\n let i;\n return this.documentOverlayCache.getOverlaysForCollection(e, t.path, n.largestBatchId).next((s => (i = s, \n this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, i, r)))).next((e => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n i.forEach(((t, n) => {\n const r = n.getKey();\n null === e.get(r) && (e = e.insert(r, MutableDocument.newInvalidDocument(r)));\n }));\n // Apply the overlays and match against the query.\n let n = documentMap();\n return e.forEach(((e, r) => {\n const s = i.get(e);\n void 0 !== s && __PRIVATE_mutationApplyToLocalView(s.mutation, r, FieldMask.empty(), Timestamp.now()), \n // Finally, insert the documents that still match the query\n __PRIVATE_queryMatches(t, r) && (n = n.insert(e, r));\n })), n;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryBundleCache {\n constructor(e) {\n this.serializer = e, this.cr = new Map, this.lr = new Map;\n }\n getBundleMetadata(e, t) {\n return PersistencePromise.resolve(this.cr.get(t));\n }\n saveBundleMetadata(e, t) {\n return this.cr.set(t.id, \n /** Decodes a BundleMetadata proto into a BundleMetadata object. */\n function __PRIVATE_fromBundleMetadata(e) {\n return {\n id: e.id,\n version: e.version,\n createTime: __PRIVATE_fromVersion(e.createTime)\n };\n }(t)), PersistencePromise.resolve();\n }\n getNamedQuery(e, t) {\n return PersistencePromise.resolve(this.lr.get(t));\n }\n saveNamedQuery(e, t) {\n return this.lr.set(t.name, function __PRIVATE_fromProtoNamedQuery(e) {\n return {\n name: e.name,\n query: __PRIVATE_fromBundledQuery(e.bundledQuery),\n readTime: __PRIVATE_fromVersion(e.readTime)\n };\n }(t)), PersistencePromise.resolve();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */ class __PRIVATE_MemoryDocumentOverlayCache {\n constructor() {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n this.overlays = new SortedMap(DocumentKey.comparator), this.hr = new Map;\n }\n getOverlay(e, t) {\n return PersistencePromise.resolve(this.overlays.get(t));\n }\n getOverlays(e, t) {\n const n = __PRIVATE_newOverlayMap();\n return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => {\n null !== e && n.set(t, e);\n })))).next((() => n));\n }\n saveOverlays(e, t, n) {\n return n.forEach(((n, r) => {\n this.ht(e, t, r);\n })), PersistencePromise.resolve();\n }\n removeOverlaysForBatchId(e, t, n) {\n const r = this.hr.get(n);\n return void 0 !== r && (r.forEach((e => this.overlays = this.overlays.remove(e))), \n this.hr.delete(n)), PersistencePromise.resolve();\n }\n getOverlaysForCollection(e, t, n) {\n const r = __PRIVATE_newOverlayMap(), i = t.length + 1, s = new DocumentKey(t.child(\"\")), o = this.overlays.getIteratorFrom(s);\n for (;o.hasNext(); ) {\n const e = o.getNext().value, s = e.getKey();\n if (!t.isPrefixOf(s.path)) break;\n // Documents from sub-collections\n s.path.length === i && (e.largestBatchId > n && r.set(e.getKey(), e));\n }\n return PersistencePromise.resolve(r);\n }\n getOverlaysForCollectionGroup(e, t, n, r) {\n let i = new SortedMap(((e, t) => e - t));\n const s = this.overlays.getIterator();\n for (;s.hasNext(); ) {\n const e = s.getNext().value;\n if (e.getKey().getCollectionGroup() === t && e.largestBatchId > n) {\n let t = i.get(e.largestBatchId);\n null === t && (t = __PRIVATE_newOverlayMap(), i = i.insert(e.largestBatchId, t)), \n t.set(e.getKey(), e);\n }\n }\n const o = __PRIVATE_newOverlayMap(), _ = i.getIterator();\n for (;_.hasNext(); ) {\n if (_.getNext().value.forEach(((e, t) => o.set(e, t))), o.size() >= r) break;\n }\n return PersistencePromise.resolve(o);\n }\n ht(e, t, n) {\n // Remove the association of the overlay to its batch id.\n const r = this.overlays.get(n.key);\n if (null !== r) {\n const e = this.hr.get(r.largestBatchId).delete(n.key);\n this.hr.set(r.largestBatchId, e);\n }\n this.overlays = this.overlays.insert(n.key, new Overlay(t, n));\n // Create the association of this overlay to the given largestBatchId.\n let i = this.hr.get(t);\n void 0 === i && (i = __PRIVATE_documentKeySet(), this.hr.set(t, i)), this.hr.set(t, i.add(n.key));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */ class __PRIVATE_ReferenceSet {\n constructor() {\n // A set of outstanding references to a document sorted by key.\n this.Pr = new SortedSet(__PRIVATE_DocReference.Ir), \n // A set of outstanding references to a document sorted by target id.\n this.Tr = new SortedSet(__PRIVATE_DocReference.Er);\n }\n /** Returns true if the reference set contains no references. */ isEmpty() {\n return this.Pr.isEmpty();\n }\n /** Adds a reference to the given document key for the given ID. */ addReference(e, t) {\n const n = new __PRIVATE_DocReference(e, t);\n this.Pr = this.Pr.add(n), this.Tr = this.Tr.add(n);\n }\n /** Add references to the given document keys for the given ID. */ dr(e, t) {\n e.forEach((e => this.addReference(e, t)));\n }\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */ removeReference(e, t) {\n this.Ar(new __PRIVATE_DocReference(e, t));\n }\n Rr(e, t) {\n e.forEach((e => this.removeReference(e, t)));\n }\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */ Vr(e) {\n const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1), i = [];\n return this.Tr.forEachInRange([ n, r ], (e => {\n this.Ar(e), i.push(e.key);\n })), i;\n }\n mr() {\n this.Pr.forEach((e => this.Ar(e)));\n }\n Ar(e) {\n this.Pr = this.Pr.delete(e), this.Tr = this.Tr.delete(e);\n }\n gr(e) {\n const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1);\n let i = __PRIVATE_documentKeySet();\n return this.Tr.forEachInRange([ n, r ], (e => {\n i = i.add(e.key);\n })), i;\n }\n containsKey(e) {\n const t = new __PRIVATE_DocReference(e, 0), n = this.Pr.firstAfterOrEqual(t);\n return null !== n && e.isEqual(n.key);\n }\n}\n\nclass __PRIVATE_DocReference {\n constructor(e, t) {\n this.key = e, this.pr = t;\n }\n /** Compare by key then by ID */ static Ir(e, t) {\n return DocumentKey.comparator(e.key, t.key) || __PRIVATE_primitiveComparator(e.pr, t.pr);\n }\n /** Compare by ID then by key */ static Er(e, t) {\n return __PRIVATE_primitiveComparator(e.pr, t.pr) || DocumentKey.comparator(e.key, t.key);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryMutationQueue {\n constructor(e, t) {\n this.indexManager = e, this.referenceDelegate = t, \n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n this.mutationQueue = [], \n /** Next value to use when assigning sequential IDs to each mutation batch. */\n this.yr = 1, \n /** An ordered mapping between documents and the mutations batch IDs. */\n this.wr = new SortedSet(__PRIVATE_DocReference.Ir);\n }\n checkEmpty(e) {\n return PersistencePromise.resolve(0 === this.mutationQueue.length);\n }\n addMutationBatch(e, t, n, r) {\n const i = this.yr;\n this.yr++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];\n const s = new MutationBatch(i, t, n, r);\n this.mutationQueue.push(s);\n // Track references by document key and index collection parents.\n for (const t of r) this.wr = this.wr.add(new __PRIVATE_DocReference(t.key, i)), \n this.indexManager.addToCollectionParentIndex(e, t.key.path.popLast());\n return PersistencePromise.resolve(s);\n }\n lookupMutationBatch(e, t) {\n return PersistencePromise.resolve(this.Sr(t));\n }\n getNextMutationBatchAfterBatchId(e, t) {\n const n = t + 1, r = this.br(n), i = r < 0 ? 0 : r;\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n return PersistencePromise.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);\n }\n getHighestUnacknowledgedBatchId() {\n return PersistencePromise.resolve(0 === this.mutationQueue.length ? -1 : this.yr - 1);\n }\n getAllMutationBatches(e) {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n getAllMutationBatchesAffectingDocumentKey(e, t) {\n const n = new __PRIVATE_DocReference(t, 0), r = new __PRIVATE_DocReference(t, Number.POSITIVE_INFINITY), i = [];\n return this.wr.forEachInRange([ n, r ], (e => {\n const t = this.Sr(e.pr);\n i.push(t);\n })), PersistencePromise.resolve(i);\n }\n getAllMutationBatchesAffectingDocumentKeys(e, t) {\n let n = new SortedSet(__PRIVATE_primitiveComparator);\n return t.forEach((e => {\n const t = new __PRIVATE_DocReference(e, 0), r = new __PRIVATE_DocReference(e, Number.POSITIVE_INFINITY);\n this.wr.forEachInRange([ t, r ], (e => {\n n = n.add(e.pr);\n }));\n })), PersistencePromise.resolve(this.Dr(n));\n }\n getAllMutationBatchesAffectingQuery(e, t) {\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const n = t.path, r = n.length + 1;\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let i = n;\n DocumentKey.isDocumentKey(i) || (i = i.child(\"\"));\n const s = new __PRIVATE_DocReference(new DocumentKey(i), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let o = new SortedSet(__PRIVATE_primitiveComparator);\n return this.wr.forEachWhile((e => {\n const t = e.key.path;\n return !!n.isPrefixOf(t) && (\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n t.length === r && (o = o.add(e.pr)), !0);\n }), s), PersistencePromise.resolve(this.Dr(o));\n }\n Dr(e) {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const t = [];\n return e.forEach((e => {\n const n = this.Sr(e);\n null !== n && t.push(n);\n })), t;\n }\n removeMutationBatch(e, t) {\n __PRIVATE_hardAssert(0 === this.Cr(t.batchId, \"removed\")), this.mutationQueue.shift();\n let n = this.wr;\n return PersistencePromise.forEach(t.mutations, (r => {\n const i = new __PRIVATE_DocReference(r.key, t.batchId);\n return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(e, r.key);\n })).next((() => {\n this.wr = n;\n }));\n }\n Mn(e) {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n containsKey(e, t) {\n const n = new __PRIVATE_DocReference(t, 0), r = this.wr.firstAfterOrEqual(n);\n return PersistencePromise.resolve(t.isEqual(r && r.key));\n }\n performConsistencyCheck(e) {\n return this.mutationQueue.length, PersistencePromise.resolve();\n }\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */ Cr(e, t) {\n return this.br(e);\n }\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */ br(e) {\n if (0 === this.mutationQueue.length) \n // As an index this is past the end of the queue\n return 0;\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n return e - this.mutationQueue[0].batchId;\n }\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */ Sr(e) {\n const t = this.br(e);\n if (t < 0 || t >= this.mutationQueue.length) return null;\n return this.mutationQueue[t];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass __PRIVATE_MemoryRemoteDocumentCacheImpl {\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(e) {\n this.vr = e, \n /** Underlying cache of documents and their read times. */\n this.docs = function __PRIVATE_documentEntryMap() {\n return new SortedMap(DocumentKey.comparator);\n }(), \n /** Size of all cached documents. */\n this.size = 0;\n }\n setIndexManager(e) {\n this.indexManager = e;\n }\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ addEntry(e, t) {\n const n = t.key, r = this.docs.get(n), i = r ? r.size : 0, s = this.vr(t);\n return this.docs = this.docs.insert(n, {\n document: t.mutableCopy(),\n size: s\n }), this.size += s - i, this.indexManager.addToCollectionParentIndex(e, n.path.popLast());\n }\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ removeEntry(e) {\n const t = this.docs.get(e);\n t && (this.docs = this.docs.remove(e), this.size -= t.size);\n }\n getEntry(e, t) {\n const n = this.docs.get(t);\n return PersistencePromise.resolve(n ? n.document.mutableCopy() : MutableDocument.newInvalidDocument(t));\n }\n getEntries(e, t) {\n let n = __PRIVATE_mutableDocumentMap();\n return t.forEach((e => {\n const t = this.docs.get(e);\n n = n.insert(e, t ? t.document.mutableCopy() : MutableDocument.newInvalidDocument(e));\n })), PersistencePromise.resolve(n);\n }\n getDocumentsMatchingQuery(e, t, n, r) {\n let i = __PRIVATE_mutableDocumentMap();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const s = t.path, o = new DocumentKey(s.child(\"\")), _ = this.docs.getIteratorFrom(o);\n for (;_.hasNext(); ) {\n const {key: e, value: {document: o}} = _.getNext();\n if (!s.isPrefixOf(e.path)) break;\n e.path.length > s.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(o), n) <= 0 || (r.has(o.key) || __PRIVATE_queryMatches(t, o)) && (i = i.insert(o.key, o.mutableCopy())));\n }\n return PersistencePromise.resolve(i);\n }\n getAllFromCollectionGroup(e, t, n, r) {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n fail();\n }\n Fr(e, t) {\n return PersistencePromise.forEach(this.docs, (e => t(e)));\n }\n newChangeBuffer(e) {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this);\n }\n getSize(e) {\n return PersistencePromise.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n constructor(e) {\n super(), this.ar = e;\n }\n applyChanges(e) {\n const t = [];\n return this.changes.forEach(((n, r) => {\n r.isValidDocument() ? t.push(this.ar.addEntry(e, r)) : this.ar.removeEntry(n);\n })), PersistencePromise.waitFor(t);\n }\n getFromCache(e, t) {\n return this.ar.getEntry(e, t);\n }\n getAllFromCache(e, t) {\n return this.ar.getEntries(e, t);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryTargetCache {\n constructor(e) {\n this.persistence = e, \n /**\n * Maps a target to the data about that target\n */\n this.Mr = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), \n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = SnapshotVersion.min(), \n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0, \n /** The highest sequence number encountered. */\n this.Or = 0, \n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.Nr = new __PRIVATE_ReferenceSet, this.targetCount = 0, this.Lr = __PRIVATE_TargetIdGenerator.Nn();\n }\n forEachTarget(e, t) {\n return this.Mr.forEach(((e, n) => t(n))), PersistencePromise.resolve();\n }\n getLastRemoteSnapshotVersion(e) {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n getHighestSequenceNumber(e) {\n return PersistencePromise.resolve(this.Or);\n }\n allocateTargetId(e) {\n return this.highestTargetId = this.Lr.next(), PersistencePromise.resolve(this.highestTargetId);\n }\n setTargetsMetadata(e, t, n) {\n return n && (this.lastRemoteSnapshotVersion = n), t > this.Or && (this.Or = t), \n PersistencePromise.resolve();\n }\n qn(e) {\n this.Mr.set(e.target, e);\n const t = e.targetId;\n t > this.highestTargetId && (this.Lr = new __PRIVATE_TargetIdGenerator(t), this.highestTargetId = t), \n e.sequenceNumber > this.Or && (this.Or = e.sequenceNumber);\n }\n addTargetData(e, t) {\n return this.qn(t), this.targetCount += 1, PersistencePromise.resolve();\n }\n updateTargetData(e, t) {\n return this.qn(t), PersistencePromise.resolve();\n }\n removeTargetData(e, t) {\n return this.Mr.delete(t.target), this.Nr.Vr(t.targetId), this.targetCount -= 1, \n PersistencePromise.resolve();\n }\n removeTargets(e, t, n) {\n let r = 0;\n const i = [];\n return this.Mr.forEach(((s, o) => {\n o.sequenceNumber <= t && null === n.get(o.targetId) && (this.Mr.delete(s), i.push(this.removeMatchingKeysForTargetId(e, o.targetId)), \n r++);\n })), PersistencePromise.waitFor(i).next((() => r));\n }\n getTargetCount(e) {\n return PersistencePromise.resolve(this.targetCount);\n }\n getTargetData(e, t) {\n const n = this.Mr.get(t) || null;\n return PersistencePromise.resolve(n);\n }\n addMatchingKeys(e, t, n) {\n return this.Nr.dr(t, n), PersistencePromise.resolve();\n }\n removeMatchingKeys(e, t, n) {\n this.Nr.Rr(t, n);\n const r = this.persistence.referenceDelegate, i = [];\n return r && t.forEach((t => {\n i.push(r.markPotentiallyOrphaned(e, t));\n })), PersistencePromise.waitFor(i);\n }\n removeMatchingKeysForTargetId(e, t) {\n return this.Nr.Vr(t), PersistencePromise.resolve();\n }\n getMatchingKeysForTargetId(e, t) {\n const n = this.Nr.gr(t);\n return PersistencePromise.resolve(n);\n }\n containsKey(e, t) {\n return PersistencePromise.resolve(this.Nr.containsKey(t));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nclass __PRIVATE_MemoryPersistence {\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(e, t) {\n this.Br = {}, this.overlays = {}, this.kr = new __PRIVATE_ListenSequence(0), this.qr = !1, \n this.qr = !0, this.referenceDelegate = e(this), this.Qr = new __PRIVATE_MemoryTargetCache(this);\n this.indexManager = new __PRIVATE_MemoryIndexManager, this.remoteDocumentCache = function __PRIVATE_newMemoryRemoteDocumentCache(e) {\n return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e);\n }((e => this.referenceDelegate.Kr(e))), this.serializer = new __PRIVATE_LocalSerializer(t), \n this.$r = new __PRIVATE_MemoryBundleCache(this.serializer);\n }\n start() {\n return Promise.resolve();\n }\n shutdown() {\n // No durable state to ensure is closed on shutdown.\n return this.qr = !1, Promise.resolve();\n }\n get started() {\n return this.qr;\n }\n setDatabaseDeletedListener() {\n // No op.\n }\n setNetworkEnabled() {\n // No op.\n }\n getIndexManager(e) {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n getDocumentOverlayCache(e) {\n let t = this.overlays[e.toKey()];\n return t || (t = new __PRIVATE_MemoryDocumentOverlayCache, this.overlays[e.toKey()] = t), \n t;\n }\n getMutationQueue(e, t) {\n let n = this.Br[e.toKey()];\n return n || (n = new __PRIVATE_MemoryMutationQueue(t, this.referenceDelegate), this.Br[e.toKey()] = n), \n n;\n }\n getTargetCache() {\n return this.Qr;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getBundleCache() {\n return this.$r;\n }\n runTransaction(e, t, n) {\n __PRIVATE_logDebug(\"MemoryPersistence\", \"Starting transaction:\", e);\n const r = new __PRIVATE_MemoryTransaction(this.kr.next());\n return this.referenceDelegate.Ur(), n(r).next((e => this.referenceDelegate.Wr(r).next((() => e)))).toPromise().then((e => (r.raiseOnCommittedEvent(), \n e)));\n }\n Gr(e, t) {\n return PersistencePromise.or(Object.values(this.Br).map((n => () => n.containsKey(e, t))));\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */ class __PRIVATE_MemoryTransaction extends PersistenceTransaction {\n constructor(e) {\n super(), this.currentSequenceNumber = e;\n }\n}\n\nclass __PRIVATE_MemoryEagerDelegate {\n constructor(e) {\n this.persistence = e, \n /** Tracks all documents that are active in Query views. */\n this.zr = new __PRIVATE_ReferenceSet, \n /** The list of documents that are potentially GCed after each transaction. */\n this.jr = null;\n }\n static Hr(e) {\n return new __PRIVATE_MemoryEagerDelegate(e);\n }\n get Jr() {\n if (this.jr) return this.jr;\n throw fail();\n }\n addReference(e, t, n) {\n return this.zr.addReference(n, t), this.Jr.delete(n.toString()), PersistencePromise.resolve();\n }\n removeReference(e, t, n) {\n return this.zr.removeReference(n, t), this.Jr.add(n.toString()), PersistencePromise.resolve();\n }\n markPotentiallyOrphaned(e, t) {\n return this.Jr.add(t.toString()), PersistencePromise.resolve();\n }\n removeTarget(e, t) {\n this.zr.Vr(t.targetId).forEach((e => this.Jr.add(e.toString())));\n const n = this.persistence.getTargetCache();\n return n.getMatchingKeysForTargetId(e, t.targetId).next((e => {\n e.forEach((e => this.Jr.add(e.toString())));\n })).next((() => n.removeTargetData(e, t)));\n }\n Ur() {\n this.jr = new Set;\n }\n Wr(e) {\n // Remove newly orphaned documents.\n const t = this.persistence.getRemoteDocumentCache().newChangeBuffer();\n return PersistencePromise.forEach(this.Jr, (n => {\n const r = DocumentKey.fromPath(n);\n return this.Yr(e, r).next((e => {\n e || t.removeEntry(r, SnapshotVersion.min());\n }));\n })).next((() => (this.jr = null, t.apply(e))));\n }\n updateLimboDocument(e, t) {\n return this.Yr(e, t).next((e => {\n e ? this.Jr.delete(t.toString()) : this.Jr.add(t.toString());\n }));\n }\n Kr(e) {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n Yr(e, t) {\n return PersistencePromise.or([ () => PersistencePromise.resolve(this.zr.containsKey(t)), () => this.persistence.getTargetCache().containsKey(e, t), () => this.persistence.Gr(e, t) ]);\n }\n}\n\nclass __PRIVATE_MemoryLruDelegate {\n constructor(e, t) {\n this.persistence = e, this.Zr = new ObjectMap((e => __PRIVATE_encodeResourcePath(e.path)), ((e, t) => e.isEqual(t))), \n this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);\n }\n static Hr(e, t) {\n return new __PRIVATE_MemoryLruDelegate(e, t);\n }\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n Ur() {}\n Wr(e) {\n return PersistencePromise.resolve();\n }\n forEachTarget(e, t) {\n return this.persistence.getTargetCache().forEachTarget(e, t);\n }\n Hn(e) {\n const t = this.Zn(e);\n return this.persistence.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t))));\n }\n Zn(e) {\n let t = 0;\n return this.Jn(e, (e => {\n t++;\n })).next((() => t));\n }\n Jn(e, t) {\n return PersistencePromise.forEach(this.Zr, ((n, r) => this.er(e, n, r).next((e => e ? PersistencePromise.resolve() : t(r)))));\n }\n removeTargets(e, t, n) {\n return this.persistence.getTargetCache().removeTargets(e, t, n);\n }\n removeOrphanedDocuments(e, t) {\n let n = 0;\n const r = this.persistence.getRemoteDocumentCache(), i = r.newChangeBuffer();\n return r.Fr(e, (r => this.er(e, r, t).next((e => {\n e || (n++, i.removeEntry(r, SnapshotVersion.min()));\n })))).next((() => i.apply(e))).next((() => n));\n }\n markPotentiallyOrphaned(e, t) {\n return this.Zr.set(t, e.currentSequenceNumber), PersistencePromise.resolve();\n }\n removeTarget(e, t) {\n const n = t.withSequenceNumber(e.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(e, n);\n }\n addReference(e, t, n) {\n return this.Zr.set(n, e.currentSequenceNumber), PersistencePromise.resolve();\n }\n removeReference(e, t, n) {\n return this.Zr.set(n, e.currentSequenceNumber), PersistencePromise.resolve();\n }\n updateLimboDocument(e, t) {\n return this.Zr.set(t, e.currentSequenceNumber), PersistencePromise.resolve();\n }\n Kr(e) {\n let t = e.key.toString().length;\n return e.isFoundDocument() && (t += __PRIVATE_estimateByteSize(e.data.value)), t;\n }\n er(e, t, n) {\n return PersistencePromise.or([ () => this.persistence.Gr(e, t), () => this.persistence.getTargetCache().containsKey(e, t), () => {\n const e = this.Zr.get(t);\n return PersistencePromise.resolve(void 0 !== e && e > n);\n } ]);\n }\n getCacheSize(e) {\n return this.persistence.getRemoteDocumentCache().getSize(e);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Performs database creation and schema upgrades. */ class __PRIVATE_SchemaConverter {\n constructor(e) {\n this.serializer = e;\n }\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */ N(e, t, n, r) {\n const i = new __PRIVATE_SimpleDbTransaction(\"createOrUpgrade\", t);\n n < 1 && r >= 1 && (!function __PRIVATE_createPrimaryClientStore(e) {\n e.createObjectStore(\"owner\");\n }(e), function __PRIVATE_createMutationQueue(e) {\n e.createObjectStore(\"mutationQueues\", {\n keyPath: \"userId\"\n });\n e.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", M, {\n unique: !0\n }), e.createObjectStore(\"documentMutations\");\n }\n /**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */ (e), __PRIVATE_createQueryCache(e), function __PRIVATE_createLegacyRemoteDocumentCache(e) {\n e.createObjectStore(\"remoteDocuments\");\n }(e));\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n let s = PersistencePromise.resolve();\n return n < 3 && r >= 3 && (\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n 0 !== n && (!function __PRIVATE_dropQueryCache(e) {\n e.deleteObjectStore(\"targetDocuments\"), e.deleteObjectStore(\"targets\"), e.deleteObjectStore(\"targetGlobal\");\n }(e), __PRIVATE_createQueryCache(e)), s = s.next((() => \n /**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\n function __PRIVATE_writeEmptyTargetGlobalEntry(e) {\n const t = e.store(\"targetGlobal\"), n = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return t.put(\"targetGlobalKey\", n);\n }(i)))), n < 4 && r >= 4 && (0 !== n && (\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n s = s.next((() => function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e, t) {\n return t.store(\"mutations\").W().next((n => {\n e.deleteObjectStore(\"mutations\");\n e.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", M, {\n unique: !0\n });\n const r = t.store(\"mutations\"), i = n.map((e => r.put(e)));\n return PersistencePromise.waitFor(i);\n }));\n }(e, i)))), s = s.next((() => {\n !function __PRIVATE_createClientMetadataStore(e) {\n e.createObjectStore(\"clientMetadata\", {\n keyPath: \"clientId\"\n });\n }(e);\n }))), n < 5 && r >= 5 && (s = s.next((() => this.Xr(i)))), n < 6 && r >= 6 && (s = s.next((() => (function __PRIVATE_createDocumentGlobalStore(e) {\n e.createObjectStore(\"remoteDocumentGlobal\");\n }(e), this.ei(i))))), n < 7 && r >= 7 && (s = s.next((() => this.ti(i)))), n < 8 && r >= 8 && (s = s.next((() => this.ni(e, i)))), \n n < 9 && r >= 9 && (s = s.next((() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n !function __PRIVATE_dropRemoteDocumentChangesStore(e) {\n e.objectStoreNames.contains(\"remoteDocumentChanges\") && e.deleteObjectStore(\"remoteDocumentChanges\");\n }(e);\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n }))), n < 10 && r >= 10 && (s = s.next((() => this.ri(i)))), n < 11 && r >= 11 && (s = s.next((() => {\n !function __PRIVATE_createBundlesStore(e) {\n e.createObjectStore(\"bundles\", {\n keyPath: \"bundleId\"\n });\n }(e), function __PRIVATE_createNamedQueriesStore(e) {\n e.createObjectStore(\"namedQueries\", {\n keyPath: \"name\"\n });\n }(e);\n }))), n < 12 && r >= 12 && (s = s.next((() => {\n !function __PRIVATE_createDocumentOverlayStore(e) {\n const t = e.createObjectStore(\"documentOverlays\", {\n keyPath: G\n });\n t.createIndex(\"collectionPathOverlayIndex\", z, {\n unique: !1\n }), t.createIndex(\"collectionGroupOverlayIndex\", j, {\n unique: !1\n });\n }(e);\n }))), n < 13 && r >= 13 && (s = s.next((() => function __PRIVATE_createRemoteDocumentCache(e) {\n const t = e.createObjectStore(\"remoteDocumentsV14\", {\n keyPath: O\n });\n t.createIndex(\"documentKeyIndex\", N), t.createIndex(\"collectionGroupIndex\", L);\n }(e))).next((() => this.ii(e, i))).next((() => e.deleteObjectStore(\"remoteDocuments\")))), \n n < 14 && r >= 14 && (s = s.next((() => this.si(e, i)))), n < 15 && r >= 15 && (s = s.next((() => function __PRIVATE_createFieldIndex(e) {\n e.createObjectStore(\"indexConfiguration\", {\n keyPath: \"indexId\",\n autoIncrement: !0\n }).createIndex(\"collectionGroupIndex\", \"collectionGroup\", {\n unique: !1\n });\n e.createObjectStore(\"indexState\", {\n keyPath: K\n }).createIndex(\"sequenceNumberIndex\", $, {\n unique: !1\n });\n e.createObjectStore(\"indexEntries\", {\n keyPath: U\n }).createIndex(\"documentKeyIndex\", W, {\n unique: !1\n });\n }(e)))), s;\n }\n ei(e) {\n let t = 0;\n return e.store(\"remoteDocuments\").Y(((e, n) => {\n t += __PRIVATE_dbDocumentSize(n);\n })).next((() => {\n const n = {\n byteSize: t\n };\n return e.store(\"remoteDocumentGlobal\").put(\"remoteDocumentGlobalKey\", n);\n }));\n }\n Xr(e) {\n const t = e.store(\"mutationQueues\"), n = e.store(\"mutations\");\n return t.W().next((t => PersistencePromise.forEach(t, (t => {\n const r = IDBKeyRange.bound([ t.userId, -1 ], [ t.userId, t.lastAcknowledgedBatchId ]);\n return n.W(\"userMutationsIndex\", r).next((n => PersistencePromise.forEach(n, (n => {\n __PRIVATE_hardAssert(n.userId === t.userId);\n const r = __PRIVATE_fromDbMutationBatch(this.serializer, n);\n return removeMutationBatch(e, t.userId, r).next((() => {}));\n }))));\n }))));\n }\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */ ti(e) {\n const t = e.store(\"targetDocuments\"), n = e.store(\"remoteDocuments\");\n return e.store(\"targetGlobal\").get(\"targetGlobalKey\").next((e => {\n const r = [];\n return n.Y(((n, i) => {\n const s = new ResourcePath(n), o = function __PRIVATE_sentinelKey(e) {\n return [ 0, __PRIVATE_encodeResourcePath(e) ];\n }(s);\n r.push(t.get(o).next((n => n ? PersistencePromise.resolve() : (n => t.put({\n targetId: 0,\n path: __PRIVATE_encodeResourcePath(n),\n sequenceNumber: e.highestListenSequenceNumber\n }))(s))));\n })).next((() => PersistencePromise.waitFor(r)));\n }));\n }\n ni(e, t) {\n // Create the index.\n e.createObjectStore(\"collectionParents\", {\n keyPath: Q\n });\n const n = t.store(\"collectionParents\"), r = new __PRIVATE_MemoryCollectionParentIndex, addEntry = e => {\n if (r.add(e)) {\n const t = e.lastSegment(), r = e.popLast();\n return n.put({\n collectionId: t,\n parent: __PRIVATE_encodeResourcePath(r)\n });\n }\n };\n // Helper to add an index entry iff we haven't already written it.\n // Index existing remote documents.\n return t.store(\"remoteDocuments\").Y({\n J: !0\n }, ((e, t) => {\n const n = new ResourcePath(e);\n return addEntry(n.popLast());\n })).next((() => t.store(\"documentMutations\").Y({\n J: !0\n }, (([e, t, n], r) => {\n const i = __PRIVATE_decodeResourcePath(t);\n return addEntry(i.popLast());\n }))));\n }\n ri(e) {\n const t = e.store(\"targets\");\n return t.Y(((e, n) => {\n const r = __PRIVATE_fromDbTarget(n), i = __PRIVATE_toDbTarget(this.serializer, r);\n return t.put(i);\n }));\n }\n ii(e, t) {\n const n = t.store(\"remoteDocuments\"), r = [];\n return n.Y(((e, n) => {\n const i = t.store(\"remoteDocumentsV14\"), s = function __PRIVATE_extractKey(e) {\n return e.document ? new DocumentKey(ResourcePath.fromString(e.document.name).popFirst(5)) : e.noDocument ? DocumentKey.fromSegments(e.noDocument.path) : e.unknownDocument ? DocumentKey.fromSegments(e.unknownDocument.path) : fail();\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n).path.toArray(), o = {\n prefixPath: s.slice(0, s.length - 2),\n collectionGroup: s[s.length - 2],\n documentId: s[s.length - 1],\n readTime: n.readTime || [ 0, 0 ],\n unknownDocument: n.unknownDocument,\n noDocument: n.noDocument,\n document: n.document,\n hasCommittedMutations: !!n.hasCommittedMutations\n };\n r.push(i.put(o));\n })).next((() => PersistencePromise.waitFor(r)));\n }\n si(e, t) {\n const n = t.store(\"mutations\"), r = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Hr, this.serializer.ct);\n return n.W().next((e => {\n const n = new Map;\n return e.forEach((e => {\n var t;\n let r = null !== (t = n.get(e.userId)) && void 0 !== t ? t : __PRIVATE_documentKeySet();\n __PRIVATE_fromDbMutationBatch(this.serializer, e).keys().forEach((e => r = r.add(e))), \n n.set(e.userId, r);\n })), PersistencePromise.forEach(n, ((e, n) => {\n const s = new User(n), o = __PRIVATE_IndexedDbDocumentOverlayCache.lt(this.serializer, s), _ = i.getIndexManager(s), a = __PRIVATE_IndexedDbMutationQueue.lt(s, this.serializer, _, i.referenceDelegate);\n return new LocalDocumentsView(r, a, o, _).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t, __PRIVATE_ListenSequence._e), e).next();\n }));\n }));\n }\n}\n\nfunction __PRIVATE_createQueryCache(e) {\n e.createObjectStore(\"targetDocuments\", {\n keyPath: k\n }).createIndex(\"documentTargetsIndex\", q, {\n unique: !0\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n e.createObjectStore(\"targets\", {\n keyPath: \"targetId\"\n }).createIndex(\"queryTargetsIndex\", B, {\n unique: !0\n }), e.createObjectStore(\"targetGlobal\");\n}\n\nconst de = \"Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.\";\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nclass __PRIVATE_IndexedDbPersistence {\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n e, t, n, r, i, s, o, _, a, \n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n u, c = 15) {\n if (this.allowTabSynchronization = e, this.persistenceKey = t, this.clientId = n, \n this.oi = i, this.window = s, this.document = o, this._i = a, this.ai = u, this.ui = c, \n this.kr = null, this.qr = !1, this.isPrimary = !1, this.networkEnabled = !0, \n /** Our window.unload handler, if registered. */\n this.ci = null, this.inForeground = !1, \n /** Our 'visibilitychange' listener if registered. */\n this.li = null, \n /** The client metadata refresh task. */\n this.hi = null, \n /** The last time we garbage collected the client metadata object store. */\n this.Pi = Number.NEGATIVE_INFINITY, \n /** A listener to notify on primary state changes. */\n this.Ii = e => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.D()) throw new FirestoreError(D.UNIMPLEMENTED, \"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.\");\n this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r), this.Ti = t + \"main\", \n this.serializer = new __PRIVATE_LocalSerializer(_), this.Ei = new __PRIVATE_SimpleDb(this.Ti, this.ui, new __PRIVATE_SchemaConverter(this.serializer)), \n this.Qr = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), \n this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), \n this.$r = new __PRIVATE_IndexedDbBundleCache, this.window && this.window.localStorage ? this.di = this.window.localStorage : (this.di = null, \n !1 === u && __PRIVATE_logError(\"IndexedDbPersistence\", \"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.\"));\n }\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */ start() {\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.Ai().then((() => {\n if (!this.isPrimary && !this.allowTabSynchronization) \n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(D.FAILED_PRECONDITION, de);\n return this.Ri(), this.Vi(), this.mi(), this.runTransaction(\"getHighestListenSequenceNumber\", \"readonly\", (e => this.Qr.getHighestSequenceNumber(e)));\n })).then((e => {\n this.kr = new __PRIVATE_ListenSequence(e, this._i);\n })).then((() => {\n this.qr = !0;\n })).catch((e => (this.Ei && this.Ei.close(), Promise.reject(e))));\n }\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ fi(e) {\n return this.Ii = async t => {\n if (this.started) return e(t);\n }, e(this.isPrimary);\n }\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setDatabaseDeletedListener(e) {\n this.Ei.B((async t => {\n // Check if an attempt is made to delete IndexedDB.\n null === t.newVersion && await e();\n }));\n }\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setNetworkEnabled(e) {\n this.networkEnabled !== e && (this.networkEnabled = e, \n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.oi.enqueueAndForget((async () => {\n this.started && await this.Ai();\n })));\n }\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */ Ai() {\n return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\", \"readwrite\", (e => __PRIVATE_clientMetadataStore(e).put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n }).next((() => {\n if (this.isPrimary) return this.gi(e).next((e => {\n e || (this.isPrimary = !1, this.oi.enqueueRetryable((() => this.Ii(!1))));\n }));\n })).next((() => this.pi(e))).next((t => this.isPrimary && !t ? this.yi(e).next((() => !1)) : !!t && this.wi(e).next((() => !0)))))).catch((e => {\n if (__PRIVATE_isIndexedDbTransactionError(e)) \n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Failed to extend owner lease: \", e), \n this.isPrimary;\n if (!this.allowTabSynchronization) throw e;\n return __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Releasing owner lease after error during lease refresh\", e), \n /* isPrimary= */ !1;\n })).then((e => {\n this.isPrimary !== e && this.oi.enqueueRetryable((() => this.Ii(e))), this.isPrimary = e;\n }));\n }\n gi(e) {\n return __PRIVATE_primaryClientStore(e).get(\"owner\").next((e => PersistencePromise.resolve(this.Si(e))));\n }\n bi(e) {\n return __PRIVATE_clientMetadataStore(e).delete(this.clientId);\n }\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */ async Di() {\n if (this.isPrimary && !this.Ci(this.Pi, 18e5)) {\n this.Pi = Date.now();\n const e = await this.runTransaction(\"maybeGarbageCollectMultiClientState\", \"readwrite-primary\", (e => {\n const t = __PRIVATE_getStore(e, \"clientMetadata\");\n return t.W().next((e => {\n const n = this.vi(e, 18e5), r = e.filter((e => -1 === n.indexOf(e)));\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(r, (e => t.delete(e.clientId))).next((() => r));\n }));\n })).catch((() => []));\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.di) for (const t of e) this.di.removeItem(this.Fi(t.clientId));\n }\n }\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */ mi() {\n this.hi = this.oi.enqueueAfterDelay(\"client_metadata_refresh\" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.Ai().then((() => this.Di())).then((() => this.mi()))));\n }\n /** Checks whether `client` is the local client. */ Si(e) {\n return !!e && e.ownerId === this.clientId;\n }\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */ pi(e) {\n if (this.ai) return PersistencePromise.resolve(!0);\n return __PRIVATE_primaryClientStore(e).get(\"owner\").next((t => {\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (null !== t && this.Ci(t.leaseTimestampMs, 5e3) && !this.Mi(t.ownerId)) {\n if (this.Si(t) && this.networkEnabled) return !0;\n if (!this.Si(t)) {\n if (!t.allowTabSynchronization) \n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(D.FAILED_PRECONDITION, de);\n return !1;\n }\n }\n return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e).W().next((e => void 0 === this.vi(e, 5e3).find((e => {\n if (this.clientId !== e.clientId) {\n const t = !this.networkEnabled && e.networkEnabled, n = !this.inForeground && e.inForeground, r = this.networkEnabled === e.networkEnabled;\n if (t || n && r) return !0;\n }\n return !1;\n }))));\n })).next((e => (this.isPrimary !== e && __PRIVATE_logDebug(\"IndexedDbPersistence\", `Client ${e ? \"is\" : \"is not\"} eligible for a primary lease.`), \n e)));\n }\n async shutdown() {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this.qr = !1, this.xi(), this.hi && (this.hi.cancel(), this.hi = null), this.Oi(), \n this.Ni(), \n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.Ei.runTransaction(\"shutdown\", \"readwrite\", [ \"owner\", \"clientMetadata\" ], (e => {\n const t = new __PRIVATE_IndexedDbTransaction(e, __PRIVATE_ListenSequence._e);\n return this.yi(t).next((() => this.bi(t)));\n })), this.Ei.close(), \n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.Li();\n }\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */ vi(e, t) {\n return e.filter((e => this.Ci(e.updateTimeMs, t) && !this.Mi(e.clientId)));\n }\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ Bi() {\n return this.runTransaction(\"getActiveClients\", \"readonly\", (e => __PRIVATE_clientMetadataStore(e).W().next((e => this.vi(e, 18e5).map((e => e.clientId))))));\n }\n get started() {\n return this.qr;\n }\n getMutationQueue(e, t) {\n return __PRIVATE_IndexedDbMutationQueue.lt(e, this.serializer, t, this.referenceDelegate);\n }\n getTargetCache() {\n return this.Qr;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getIndexManager(e) {\n return new __PRIVATE_IndexedDbIndexManager(e, this.serializer.ct.databaseId);\n }\n getDocumentOverlayCache(e) {\n return __PRIVATE_IndexedDbDocumentOverlayCache.lt(this.serializer, e);\n }\n getBundleCache() {\n return this.$r;\n }\n runTransaction(e, t, n) {\n __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Starting transaction:\", e);\n const r = \"readonly\" === t ? \"readonly\" : \"readwrite\", i = \n /** Returns the object stores for the provided schema. */\n function __PRIVATE_getObjectStores(e) {\n return 15 === e ? X : 14 === e ? Z : 13 === e ? Y : 12 === e ? J : 11 === e ? H : void fail();\n }(this.ui);\n let s;\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.Ei.runTransaction(e, r, i, (r => (s = new __PRIVATE_IndexedDbTransaction(r, this.kr ? this.kr.next() : __PRIVATE_ListenSequence._e), \n \"readwrite-primary\" === t ? this.gi(s).next((e => !!e || this.pi(s))).next((t => {\n if (!t) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`), \n this.isPrimary = !1, this.oi.enqueueRetryable((() => this.Ii(!1))), new FirestoreError(D.FAILED_PRECONDITION, v);\n return n(s);\n })).next((e => this.wi(s).next((() => e)))) : this.ki(s).next((() => n(s)))))).then((e => (s.raiseOnCommittedEvent(), \n e)));\n }\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n ki(e) {\n return __PRIVATE_primaryClientStore(e).get(\"owner\").next((e => {\n if (null !== e && this.Ci(e.leaseTimestampMs, 5e3) && !this.Mi(e.ownerId) && !this.Si(e) && !(this.ai || this.allowTabSynchronization && e.allowTabSynchronization)) throw new FirestoreError(D.FAILED_PRECONDITION, de);\n }));\n }\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */ wi(e) {\n const t = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return __PRIVATE_primaryClientStore(e).put(\"owner\", t);\n }\n static D() {\n return __PRIVATE_SimpleDb.D();\n }\n /** Checks the primary lease and removes it if we are the current primary. */ yi(e) {\n const t = __PRIVATE_primaryClientStore(e);\n return t.get(\"owner\").next((e => this.Si(e) ? (__PRIVATE_logDebug(\"IndexedDbPersistence\", \"Releasing primary lease.\"), \n t.delete(\"owner\")) : PersistencePromise.resolve()));\n }\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ Ci(e, t) {\n const n = Date.now();\n return !(e < n - t) && (!(e > n) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${n}`), \n !1));\n }\n Ri() {\n null !== this.document && \"function\" == typeof this.document.addEventListener && (this.li = () => {\n this.oi.enqueueAndForget((() => (this.inForeground = \"visible\" === this.document.visibilityState, \n this.Ai())));\n }, this.document.addEventListener(\"visibilitychange\", this.li), this.inForeground = \"visible\" === this.document.visibilityState);\n }\n Oi() {\n this.li && (this.document.removeEventListener(\"visibilitychange\", this.li), this.li = null);\n }\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */ Vi() {\n var e;\n \"function\" == typeof (null === (e = this.window) || void 0 === e ? void 0 : e.addEventListener) && (this.ci = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.xi();\n const e = /(?:Version|Mobile)\\/1[456]/;\n (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.isSafari)() && (navigator.appVersion.match(e) || navigator.userAgent.match(e)) && \n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.oi.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.oi.enqueueAndForget((() => this.shutdown()));\n }, this.window.addEventListener(\"pagehide\", this.ci));\n }\n Ni() {\n this.ci && (this.window.removeEventListener(\"pagehide\", this.ci), this.ci = null);\n }\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */ Mi(e) {\n var t;\n try {\n const n = null !== (null === (t = this.di) || void 0 === t ? void 0 : t.getItem(this.Fi(e)));\n return __PRIVATE_logDebug(\"IndexedDbPersistence\", `Client '${e}' ${n ? \"is\" : \"is not\"} zombied in LocalStorage`), \n n;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n return __PRIVATE_logError(\"IndexedDbPersistence\", \"Failed to get zombied client id.\", e), \n !1;\n }\n }\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */ xi() {\n if (this.di) try {\n this.di.setItem(this.Fi(this.clientId), String(Date.now()));\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n __PRIVATE_logError(\"Failed to set zombie client id.\", e);\n }\n }\n /** Removes the zombied client entry if it exists. */ Li() {\n if (this.di) try {\n this.di.removeItem(this.Fi(this.clientId));\n } catch (e) {\n // Ignore\n }\n }\n Fi(e) {\n return `firestore_zombie_${this.persistenceKey}_${e}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */ function __PRIVATE_primaryClientStore(e) {\n return __PRIVATE_getStore(e, \"owner\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */ function __PRIVATE_clientMetadataStore(e) {\n return __PRIVATE_getStore(e, \"clientMetadata\");\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */ function __PRIVATE_indexedDbStoragePrefix(e, t) {\n // Use two different prefix formats:\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let n = e.projectId;\n return e.isDefaultDatabase || (n += \".\" + e.database), \"firestore/\" + t + \"/\" + n + \"/\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nclass __PRIVATE_LocalViewChanges {\n constructor(e, t, n, r) {\n this.targetId = e, this.fromCache = t, this.qi = n, this.Qi = r;\n }\n static Ki(e, t) {\n let n = __PRIVATE_documentKeySet(), r = __PRIVATE_documentKeySet();\n for (const e of t.docChanges) switch (e.type) {\n case 0 /* ChangeType.Added */ :\n n = n.add(e.doc.key);\n break;\n\n case 1 /* ChangeType.Removed */ :\n r = r.add(e.doc.key);\n // do nothing\n }\n return new __PRIVATE_LocalViewChanges(e, t.fromCache, n, r);\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A tracker to keep a record of important details during database local query\n * execution.\n */ class QueryContext {\n constructor() {\n /**\n * Counts the number of documents passed through during local query execution.\n */\n this._documentReadCount = 0;\n }\n get documentReadCount() {\n return this._documentReadCount;\n }\n incrementDocumentReadCount(e) {\n this._documentReadCount += e;\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */\nclass __PRIVATE_QueryEngine {\n constructor() {\n this.$i = !1, this.Ui = !1, \n /**\n * SDK only decides whether it should create index when collection size is\n * larger than this.\n */\n this.Wi = 100, this.Gi = \n /**\n * This cost represents the evaluation result of\n * (([index, docKey] + [docKey, docContent]) per document in the result set)\n * / ([docKey, docContent] per documents in full collection scan) coming from\n * experiment [enter PR experiment URL here].\n */\n function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument() {\n // These values were derived from an experiment where several members of the\n // Firestore SDK team ran a performance test in various environments.\n // Googlers can see b/299284287 for details.\n return (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.isSafari)() ? 8 : __PRIVATE_SimpleDb.v((0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getUA)()) > 0 ? 6 : 4;\n }();\n }\n /** Sets the document view to query against. */ initialize(e, t) {\n this.zi = e, this.indexManager = t, this.$i = !0;\n }\n /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(e, t, n, r) {\n // Stores the result from executing the query; using this object is more\n // convenient than passing the result between steps of the persistence\n // transaction and improves readability comparatively.\n const i = {\n result: null\n };\n return this.ji(e, t).next((e => {\n i.result = e;\n })).next((() => {\n if (!i.result) return this.Hi(e, t, r, n).next((e => {\n i.result = e;\n }));\n })).next((() => {\n if (i.result) return;\n const n = new QueryContext;\n return this.Ji(e, t, n).next((r => {\n if (i.result = r, this.Ui) return this.Yi(e, t, n, r.size);\n }));\n })).next((() => i.result));\n }\n Yi(e, t, n, r) {\n return n.documentReadCount < this.Wi ? (__PRIVATE_getLogLevel() <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"SDK will not create cache indexes for query:\", __PRIVATE_stringifyQuery(t), \"since it only creates cache indexes for collection contains\", \"more than or equal to\", this.Wi, \"documents\"), \n PersistencePromise.resolve()) : (__PRIVATE_getLogLevel() <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"Query:\", __PRIVATE_stringifyQuery(t), \"scans\", n.documentReadCount, \"local documents and returns\", r, \"documents as results.\"), \n n.documentReadCount > this.Gi * r ? (__PRIVATE_getLogLevel() <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"The SDK decides to create cache indexes for query:\", __PRIVATE_stringifyQuery(t), \"as using cache indexes may help improve performance.\"), \n this.indexManager.createTargetIndexes(e, __PRIVATE_queryToTarget(t))) : PersistencePromise.resolve());\n }\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */ ji(e, t) {\n if (__PRIVATE_queryMatchesAllDocuments(t)) \n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve(null);\n let n = __PRIVATE_queryToTarget(t);\n return this.indexManager.getIndexType(e, n).next((r => 0 /* IndexType.NONE */ === r ? null : (null !== t.limit && 1 /* IndexType.PARTIAL */ === r && (\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n t = __PRIVATE_queryWithLimit(t, null, \"F\" /* LimitType.First */), n = __PRIVATE_queryToTarget(t)), \n this.indexManager.getDocumentsMatchingTarget(e, n).next((r => {\n const i = __PRIVATE_documentKeySet(...r);\n return this.zi.getDocuments(e, i).next((r => this.indexManager.getMinOffset(e, n).next((n => {\n const s = this.Zi(t, r);\n return this.Xi(t, s, i, n.readTime) ? this.ji(e, __PRIVATE_queryWithLimit(t, null, \"F\" /* LimitType.First */)) : this.es(e, s, t, n);\n }))));\n })))));\n }\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */ Hi(e, t, n, r) {\n return __PRIVATE_queryMatchesAllDocuments(t) || r.isEqual(SnapshotVersion.min()) ? PersistencePromise.resolve(null) : this.zi.getDocuments(e, n).next((i => {\n const s = this.Zi(t, i);\n return this.Xi(t, s, n, r) ? PersistencePromise.resolve(null) : (__PRIVATE_getLogLevel() <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"Re-using previous result from %s to execute query: %s\", r.toString(), __PRIVATE_stringifyQuery(t)), \n this.es(e, s, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, -1)).next((e => e)));\n }));\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n }\n /** Applies the query filter and sorting to the provided documents. */ Zi(e, t) {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let n = new SortedSet(__PRIVATE_newQueryComparator(e));\n return t.forEach(((t, r) => {\n __PRIVATE_queryMatches(e, r) && (n = n.add(r));\n })), n;\n }\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */ Xi(e, t, n, r) {\n if (null === e.limit) \n // Queries without limits do not need to be refilled.\n return !1;\n if (n.size !== t.size) \n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return !0;\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const i = \"F\" /* LimitType.First */ === e.limitType ? t.last() : t.first();\n return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0);\n }\n Ji(e, t, n) {\n return __PRIVATE_getLogLevel() <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"Using full collection scan to execute query:\", __PRIVATE_stringifyQuery(t)), \n this.zi.getDocumentsMatchingQuery(e, t, IndexOffset.min(), n);\n }\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */ es(e, t, n, r) {\n // Retrieve all results for documents that were updated since the offset.\n return this.zi.getDocumentsMatchingQuery(e, n, r).next((e => (\n // Merge with existing results\n t.forEach((t => {\n e = e.insert(t.key, t);\n })), e)));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass __PRIVATE_LocalStoreImpl {\n constructor(\n /** Manages our in-memory or durable persistence. */\n e, t, n, r) {\n this.persistence = e, this.ts = t, this.serializer = r, \n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n this.ns = new SortedMap(__PRIVATE_primitiveComparator), \n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n this.rs = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), \n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n this.ss = new Map, this.os = e.getRemoteDocumentCache(), this.Qr = e.getTargetCache(), \n this.$r = e.getBundleCache(), this._s(n);\n }\n _s(e) {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e), this.indexManager = this.persistence.getIndexManager(e), \n this.mutationQueue = this.persistence.getMutationQueue(e, this.indexManager), this.localDocuments = new LocalDocumentsView(this.os, this.mutationQueue, this.documentOverlayCache, this.indexManager), \n this.os.setIndexManager(this.indexManager), this.ts.initialize(this.localDocuments, this.indexManager);\n }\n collectGarbage(e) {\n return this.persistence.runTransaction(\"Collect garbage\", \"readwrite-primary\", (t => e.collect(t, this.ns)));\n }\n}\n\nfunction __PRIVATE_newLocalStore(\n/** Manages our in-memory or durable persistence. */\ne, t, n, r) {\n return new __PRIVATE_LocalStoreImpl(e, t, n, r);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nasync function __PRIVATE_localStoreHandleUserChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n return await n.persistence.runTransaction(\"Handle user change\", \"readonly\", (e => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let r;\n return n.mutationQueue.getAllMutationBatches(e).next((i => (r = i, n._s(t), n.mutationQueue.getAllMutationBatches(e)))).next((t => {\n const i = [], s = [];\n // Union the old/new changed keys.\n let o = __PRIVATE_documentKeySet();\n for (const e of r) {\n i.push(e.batchId);\n for (const t of e.mutations) o = o.add(t.key);\n }\n for (const e of t) {\n s.push(e.batchId);\n for (const t of e.mutations) o = o.add(t.key);\n }\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return n.localDocuments.getDocuments(e, o).next((e => ({\n us: e,\n removedBatchIds: i,\n addedBatchIds: s\n })));\n }));\n }));\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nfunction __PRIVATE_localStoreAcknowledgeBatch(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Acknowledge batch\", \"readwrite-primary\", (e => {\n const r = t.batch.keys(), i = n.os.newChangeBuffer({\n trackRemovals: !0\n });\n return function __PRIVATE_applyWriteToRemoteDocuments(e, t, n, r) {\n const i = n.batch, s = i.keys();\n let o = PersistencePromise.resolve();\n return s.forEach((e => {\n o = o.next((() => r.getEntry(t, e))).next((t => {\n const s = n.docVersions.get(e);\n __PRIVATE_hardAssert(null !== s), t.version.compareTo(s) < 0 && (i.applyToRemoteDocument(t, n), \n t.isValidDocument() && (\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n t.setReadTime(n.commitVersion), r.addEntry(t)));\n }));\n })), o.next((() => e.mutationQueue.removeMutationBatch(t, i)));\n }\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-Tab only.\n (n, e, t, i).next((() => i.apply(e))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, function __PRIVATE_getKeysWithTransformResults(e) {\n let t = __PRIVATE_documentKeySet();\n for (let n = 0; n < e.mutationResults.length; ++n) {\n e.mutationResults[n].transformResults.length > 0 && (t = t.add(e.batch.mutations[n].key));\n }\n return t;\n }\n /**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */ (t)))).next((() => n.localDocuments.getDocuments(e, r)));\n }));\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nfunction __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e) {\n const t = __PRIVATE_debugCast(e);\n return t.persistence.runTransaction(\"Get last remote snapshot version\", \"readonly\", (e => t.Qr.getLastRemoteSnapshotVersion(e)));\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */ function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e, t) {\n const n = __PRIVATE_debugCast(e), r = t.snapshotVersion;\n let i = n.ns;\n return n.persistence.runTransaction(\"Apply remote event\", \"readwrite-primary\", (e => {\n const s = n.os.newChangeBuffer({\n trackRemovals: !0\n });\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n i = n.ns;\n const o = [];\n t.targetChanges.forEach(((s, _) => {\n const a = i.get(_);\n if (!a) return;\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n o.push(n.Qr.removeMatchingKeys(e, s.removedDocuments, _).next((() => n.Qr.addMatchingKeys(e, s.addedDocuments, _))));\n let u = a.withSequenceNumber(e.currentSequenceNumber);\n null !== t.targetMismatches.get(_) ? u = u.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s.resumeToken.approximateByteSize() > 0 && (u = u.withResumeToken(s.resumeToken, r)), \n i = i.insert(_, u), \n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n /**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\n function __PRIVATE_shouldPersistTargetData(e, t, n) {\n // Always persist target data if we don't already have a resume token.\n if (0 === e.resumeToken.approximateByteSize()) return !0;\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n if (t.snapshotVersion.toMicroseconds() - e.snapshotVersion.toMicroseconds() >= 3e8) return !0;\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;\n }\n /**\n * Notifies local store of the changed views to locally pin documents.\n */ (a, u, s) && o.push(n.Qr.updateTargetData(e, u));\n }));\n let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (t.documentUpdates.forEach((r => {\n t.resolvedLimboDocuments.has(r) && o.push(n.persistence.referenceDelegate.updateLimboDocument(e, r));\n })), \n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n o.push(__PRIVATE_populateDocumentChangeBuffer(e, s, t.documentUpdates).next((e => {\n _ = e.cs, a = e.ls;\n }))), !r.isEqual(SnapshotVersion.min())) {\n const t = n.Qr.getLastRemoteSnapshotVersion(e).next((t => n.Qr.setTargetsMetadata(e, e.currentSequenceNumber, r)));\n o.push(t);\n }\n return PersistencePromise.waitFor(o).next((() => s.apply(e))).next((() => n.localDocuments.getLocalViewOfDocuments(e, _, a))).next((() => _));\n })).then((e => (n.ns = i, e)));\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */ function __PRIVATE_populateDocumentChangeBuffer(e, t, n) {\n let r = __PRIVATE_documentKeySet(), i = __PRIVATE_documentKeySet();\n return n.forEach((e => r = r.add(e))), t.getEntries(e, r).next((e => {\n let r = __PRIVATE_mutableDocumentMap();\n return n.forEach(((n, s) => {\n const o = e.get(n);\n // Check if see if there is a existence state change for this document.\n s.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), \n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n s.isNoDocument() && s.version.isEqual(SnapshotVersion.min()) ? (\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n t.removeEntry(n, s.readTime), r = r.insert(n, s)) : !o.isValidDocument() || s.version.compareTo(o.version) > 0 || 0 === s.version.compareTo(o.version) && o.hasPendingWrites ? (t.addEntry(s), \n r = r.insert(n, s)) : __PRIVATE_logDebug(\"LocalStore\", \"Ignoring outdated watch update for \", n, \". Current version:\", o.version, \" Watch version:\", s.version);\n })), {\n cs: r,\n ls: i\n };\n }));\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nfunction __PRIVATE_localStoreGetNextMutationBatch(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Get next mutation batch\", \"readonly\", (e => (void 0 === t && (t = -1), \n n.mutationQueue.getNextMutationBatchAfterBatchId(e, t))));\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nfunction __PRIVATE_localStoreAllocateTarget(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Allocate target\", \"readwrite\", (e => {\n let r;\n return n.Qr.getTargetData(e, t).next((i => i ? (\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n r = i, PersistencePromise.resolve(r)) : n.Qr.allocateTargetId(e).next((i => (r = new TargetData(t, i, \"TargetPurposeListen\" /* TargetPurpose.Listen */ , e.currentSequenceNumber), \n n.Qr.addTargetData(e, r).next((() => r)))))));\n })).then((e => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const r = n.ns.get(e.targetId);\n return (null === r || e.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.ns = n.ns.insert(e.targetId, e), \n n.rs.set(t, e.targetId)), e;\n }));\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nasync function __PRIVATE_localStoreReleaseTarget(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = r.ns.get(t), s = n ? \"readwrite\" : \"readwrite-primary\";\n try {\n n || await r.persistence.runTransaction(\"Release target\", s, (e => r.persistence.referenceDelegate.removeTarget(e, i)));\n } catch (e) {\n if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n __PRIVATE_logDebug(\"LocalStore\", `Failed to update sequence numbers for target ${t}: ${e}`);\n }\n r.ns = r.ns.remove(t), r.rs.delete(i.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */ function __PRIVATE_localStoreExecuteQuery(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n let i = SnapshotVersion.min(), s = __PRIVATE_documentKeySet();\n return r.persistence.runTransaction(\"Execute query\", \"readwrite\", (// Use readwrite instead of readonly so indexes can be created\n // Use readwrite instead of readonly so indexes can be created\n e => function __PRIVATE_localStoreGetTargetData(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = r.rs.get(n);\n return void 0 !== i ? PersistencePromise.resolve(r.ns.get(i)) : r.Qr.getTargetData(t, n);\n }(r, e, __PRIVATE_queryToTarget(t)).next((t => {\n if (t) return i = t.lastLimboFreeSnapshotVersion, r.Qr.getMatchingKeysForTargetId(e, t.targetId).next((e => {\n s = e;\n }));\n })).next((() => r.ts.getDocumentsMatchingQuery(e, t, n ? i : SnapshotVersion.min(), n ? s : __PRIVATE_documentKeySet()))).next((e => (__PRIVATE_setMaxReadTime(r, __PRIVATE_queryCollectionGroup(t), e), \n {\n documents: e,\n hs: s\n })))));\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_localStoreGetCachedTarget(e, t) {\n const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.Qr), i = n.ns.get(t);\n return i ? Promise.resolve(i.target) : n.persistence.runTransaction(\"Get target data\", \"readonly\", (e => r._t(e, t).next((e => e ? e.target : null))));\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_localStoreGetNewDocumentChanges(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.ss.get(t) || SnapshotVersion.min();\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n return n.persistence.runTransaction(\"Get new document changes\", \"readonly\", (e => n.os.getAllFromCollectionGroup(e, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, -1), \n /* limit= */ Number.MAX_SAFE_INTEGER))).then((e => (__PRIVATE_setMaxReadTime(n, t, e), \n e)));\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_setMaxReadTime(e, t, n) {\n let r = e.ss.get(t) || SnapshotVersion.min();\n n.forEach(((e, t) => {\n t.readTime.compareTo(r) > 0 && (r = t.readTime);\n })), e.ss.set(t, r);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nasync function __PRIVATE_localStoreApplyBundledDocuments(e, t, n, r) {\n const i = __PRIVATE_debugCast(e);\n let s = __PRIVATE_documentKeySet(), o = __PRIVATE_mutableDocumentMap();\n for (const e of n) {\n const n = t.Ps(e.metadata.name);\n e.document && (s = s.add(n));\n const r = t.Is(e);\n r.setReadTime(t.Ts(e.metadata.readTime)), o = o.insert(n, r);\n }\n const _ = i.os.newChangeBuffer({\n trackRemovals: !0\n }), a = await __PRIVATE_localStoreAllocateTarget(i, function __PRIVATE_umbrellaTarget(e) {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`)));\n }(r));\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n return i.persistence.runTransaction(\"Apply bundle documents\", \"readwrite\", (e => __PRIVATE_populateDocumentChangeBuffer(e, _, o).next((t => (_.apply(e), \n t))).next((t => i.Qr.removeMatchingKeysForTargetId(e, a.targetId).next((() => i.Qr.addMatchingKeys(e, s, a.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(e, t.cs, t.ls))).next((() => t.cs))))));\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nasync function __PRIVATE_localStoreSaveNamedQuery(e, t, n = __PRIVATE_documentKeySet()) {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const r = await __PRIVATE_localStoreAllocateTarget(e, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t.bundledQuery))), i = __PRIVATE_debugCast(e);\n return i.persistence.runTransaction(\"Save named query\", \"readwrite\", (e => {\n const s = __PRIVATE_fromVersion(t.readTime);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (r.snapshotVersion.compareTo(s) >= 0) return i.$r.saveNamedQuery(e, t);\n // Update existing target data because the query from the bundle is newer.\n const o = r.withResumeToken(ByteString.EMPTY_BYTE_STRING, s);\n return i.ns = i.ns.insert(o.targetId, o), i.Qr.updateTargetData(e, o).next((() => i.Qr.removeMatchingKeysForTargetId(e, r.targetId))).next((() => i.Qr.addMatchingKeys(e, n, r.targetId))).next((() => i.$r.saveNamedQuery(e, t)));\n }));\n}\n\n/** Assembles the key for a client state in WebStorage */\nfunction createWebStorageClientStateKey(e, t) {\n return `firestore_clients_${e}_${t}`;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n/** Assembles the key for a mutation batch in WebStorage */\nfunction createWebStorageMutationBatchKey(e, t, n) {\n let r = `firestore_mutations_${e}_${n}`;\n return t.isAuthenticated() && (r += `_${t.uid}`), r;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\n/** Assembles the key for a query state in WebStorage */\nfunction createWebStorageQueryTargetMetadataKey(e, t) {\n return `firestore_targets_${e}_${t}`;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nclass __PRIVATE_MutationMetadata {\n constructor(e, t, n, r) {\n this.user = e, this.batchId = t, this.state = n, this.error = r;\n }\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Es(e, t, n) {\n const r = JSON.parse(n);\n let i, s = \"object\" == typeof r && -1 !== [ \"pending\", \"acknowledged\", \"rejected\" ].indexOf(r.state) && (void 0 === r.error || \"object\" == typeof r.error);\n return s && r.error && (s = \"string\" == typeof r.error.message && \"string\" == typeof r.error.code, \n s && (i = new FirestoreError(r.error.code, r.error.message))), s ? new __PRIVATE_MutationMetadata(e, t, r.state, i) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse mutation state for ID '${t}': ${n}`), \n null);\n }\n ds() {\n const e = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (e.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(e);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nclass __PRIVATE_QueryTargetMetadata {\n constructor(e, t, n) {\n this.targetId = e, this.state = t, this.error = n;\n }\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Es(e, t) {\n const n = JSON.parse(t);\n let r, i = \"object\" == typeof n && -1 !== [ \"not-current\", \"current\", \"rejected\" ].indexOf(n.state) && (void 0 === n.error || \"object\" == typeof n.error);\n return i && n.error && (i = \"string\" == typeof n.error.message && \"string\" == typeof n.error.code, \n i && (r = new FirestoreError(n.error.code, n.error.message))), i ? new __PRIVATE_QueryTargetMetadata(e, n.state, r) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse target state for ID '${e}': ${t}`), \n null);\n }\n ds() {\n const e = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (e.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(e);\n }\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */ class __PRIVATE_RemoteClientState {\n constructor(e, t) {\n this.clientId = e, this.activeTargetIds = t;\n }\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Es(e, t) {\n const n = JSON.parse(t);\n let r = \"object\" == typeof n && n.activeTargetIds instanceof Array, i = __PRIVATE_targetIdSet();\n for (let e = 0; r && e < n.activeTargetIds.length; ++e) r = isSafeInteger(n.activeTargetIds[e]), \n i = i.add(n.activeTargetIds[e]);\n return r ? new __PRIVATE_RemoteClientState(e, i) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse client data for instance '${e}': ${t}`), \n null);\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */ class __PRIVATE_SharedOnlineState {\n constructor(e, t) {\n this.clientId = e, this.onlineState = t;\n }\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Es(e) {\n const t = JSON.parse(e);\n return \"object\" == typeof t && -1 !== [ \"Unknown\", \"Online\", \"Offline\" ].indexOf(t.onlineState) && \"string\" == typeof t.clientId ? new __PRIVATE_SharedOnlineState(t.clientId, t.onlineState) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse online state: ${e}`), \n null);\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nclass __PRIVATE_LocalClientState {\n constructor() {\n this.activeTargetIds = __PRIVATE_targetIdSet();\n }\n As(e) {\n this.activeTargetIds = this.activeTargetIds.add(e);\n }\n Rs(e) {\n this.activeTargetIds = this.activeTargetIds.delete(e);\n }\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */ ds() {\n const e = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now()\n };\n return JSON.stringify(e);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */ class __PRIVATE_WebStorageSharedClientState {\n constructor(e, t, n, r, i) {\n this.window = e, this.oi = t, this.persistenceKey = n, this.Vs = r, this.syncEngine = null, \n this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.fs = this.gs.bind(this), \n this.ps = new SortedMap(__PRIVATE_primitiveComparator), this.started = !1, \n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n this.ys = [];\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const s = n.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n this.storage = this.window.localStorage, this.currentUser = i, this.ws = createWebStorageClientStateKey(this.persistenceKey, this.Vs), \n this.Ss = \n /** Assembles the key for the current sequence number. */\n function createWebStorageSequenceNumberKey(e) {\n return `firestore_sequence_number_${e}`;\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (this.persistenceKey), this.ps = this.ps.insert(this.Vs, new __PRIVATE_LocalClientState), \n this.bs = new RegExp(`^firestore_clients_${s}_([^_]*)$`), this.Ds = new RegExp(`^firestore_mutations_${s}_(\\\\d+)(?:_(.*))?$`), \n this.Cs = new RegExp(`^firestore_targets_${s}_(\\\\d+)$`), this.vs = \n /** Assembles the key for the online state of the primary tab. */\n function createWebStorageOnlineStateKey(e) {\n return `firestore_online_state_${e}`;\n }\n // The WebStorage prefix that plays as a event to indicate the remote documents\n // might have changed due to some secondary tabs loading a bundle.\n // format of the key is:\n // firestore_bundle_loaded_v2_\n // The version ending with \"v2\" stores the list of modified collection groups.\n (this.persistenceKey), this.Fs = function createBundleLoadedKey(e) {\n return `firestore_bundle_loaded_v2_${e}`;\n }\n // The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n // looks like 'firestore_sequence_number_'.\n (this.persistenceKey), \n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener(\"storage\", this.fs);\n }\n /** Returns 'true' if WebStorage is available in the current environment. */ static D(e) {\n return !(!e || !e.localStorage);\n }\n async start() {\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const e = await this.syncEngine.Bi();\n for (const t of e) {\n if (t === this.Vs) continue;\n const e = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t));\n if (e) {\n const n = __PRIVATE_RemoteClientState.Es(t, e);\n n && (this.ps = this.ps.insert(n.clientId, n));\n }\n }\n this.Ms();\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const t = this.storage.getItem(this.vs);\n if (t) {\n const e = this.xs(t);\n e && this.Os(e);\n }\n for (const e of this.ys) this.gs(e);\n this.ys = [], \n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener(\"pagehide\", (() => this.shutdown())), this.started = !0;\n }\n writeSequenceNumber(e) {\n this.setItem(this.Ss, JSON.stringify(e));\n }\n getAllActiveQueryTargets() {\n return this.Ns(this.ps);\n }\n isActiveQueryTarget(e) {\n let t = !1;\n return this.ps.forEach(((n, r) => {\n r.activeTargetIds.has(e) && (t = !0);\n })), t;\n }\n addPendingMutation(e) {\n this.Ls(e, \"pending\");\n }\n updateMutationState(e, t, n) {\n this.Ls(e, t, n), \n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.Bs(e);\n }\n addLocalQueryTarget(e) {\n let t = \"not-current\";\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(e)) {\n const n = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));\n if (n) {\n const r = __PRIVATE_QueryTargetMetadata.Es(e, n);\n r && (t = r.state);\n }\n }\n return this.ks.As(e), this.Ms(), t;\n }\n removeLocalQueryTarget(e) {\n this.ks.Rs(e), this.Ms();\n }\n isLocalQueryTarget(e) {\n return this.ks.activeTargetIds.has(e);\n }\n clearQueryState(e) {\n this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));\n }\n updateQueryState(e, t, n) {\n this.qs(e, t, n);\n }\n handleUserChange(e, t, n) {\n t.forEach((e => {\n this.Bs(e);\n })), this.currentUser = e, n.forEach((e => {\n this.addPendingMutation(e);\n }));\n }\n setOnlineState(e) {\n this.Qs(e);\n }\n notifyBundleLoaded(e) {\n this.Ks(e);\n }\n shutdown() {\n this.started && (this.window.removeEventListener(\"storage\", this.fs), this.removeItem(this.ws), \n this.started = !1);\n }\n getItem(e) {\n const t = this.storage.getItem(e);\n return __PRIVATE_logDebug(\"SharedClientState\", \"READ\", e, t), t;\n }\n setItem(e, t) {\n __PRIVATE_logDebug(\"SharedClientState\", \"SET\", e, t), this.storage.setItem(e, t);\n }\n removeItem(e) {\n __PRIVATE_logDebug(\"SharedClientState\", \"REMOVE\", e), this.storage.removeItem(e);\n }\n gs(e) {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const t = e;\n if (t.storageArea === this.storage) {\n if (__PRIVATE_logDebug(\"SharedClientState\", \"EVENT\", t.key, t.newValue), t.key === this.ws) return void __PRIVATE_logError(\"Received WebStorage notification for local change. Another client might have garbage-collected our state\");\n this.oi.enqueueRetryable((async () => {\n if (this.started) {\n if (null !== t.key) if (this.bs.test(t.key)) {\n if (null == t.newValue) {\n const e = this.$s(t.key);\n return this.Us(e, null);\n }\n {\n const e = this.Ws(t.key, t.newValue);\n if (e) return this.Us(e.clientId, e);\n }\n } else if (this.Ds.test(t.key)) {\n if (null !== t.newValue) {\n const e = this.Gs(t.key, t.newValue);\n if (e) return this.zs(e);\n }\n } else if (this.Cs.test(t.key)) {\n if (null !== t.newValue) {\n const e = this.js(t.key, t.newValue);\n if (e) return this.Hs(e);\n }\n } else if (t.key === this.vs) {\n if (null !== t.newValue) {\n const e = this.xs(t.newValue);\n if (e) return this.Os(e);\n }\n } else if (t.key === this.Ss) {\n const e = function __PRIVATE_fromWebStorageSequenceNumber(e) {\n let t = __PRIVATE_ListenSequence._e;\n if (null != e) try {\n const n = JSON.parse(e);\n __PRIVATE_hardAssert(\"number\" == typeof n), t = n;\n } catch (e) {\n __PRIVATE_logError(\"SharedClientState\", \"Failed to read sequence number from WebStorage\", e);\n }\n return t;\n }\n /**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */ (t.newValue);\n e !== __PRIVATE_ListenSequence._e && this.sequenceNumberHandler(e);\n } else if (t.key === this.Fs) {\n const e = this.Js(t.newValue);\n await Promise.all(e.map((e => this.syncEngine.Ys(e))));\n }\n } else this.ys.push(t);\n }));\n }\n }\n get ks() {\n return this.ps.get(this.Vs);\n }\n Ms() {\n this.setItem(this.ws, this.ks.ds());\n }\n Ls(e, t, n) {\n const r = new __PRIVATE_MutationMetadata(this.currentUser, e, t, n), i = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);\n this.setItem(i, r.ds());\n }\n Bs(e) {\n const t = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);\n this.removeItem(t);\n }\n Qs(e) {\n const t = {\n clientId: this.Vs,\n onlineState: e\n };\n this.storage.setItem(this.vs, JSON.stringify(t));\n }\n qs(e, t, n) {\n const r = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e), i = new __PRIVATE_QueryTargetMetadata(e, t, n);\n this.setItem(r, i.ds());\n }\n Ks(e) {\n const t = JSON.stringify(Array.from(e));\n this.setItem(this.Fs, t);\n }\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */ $s(e) {\n const t = this.bs.exec(e);\n return t ? t[1] : null;\n }\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */ Ws(e, t) {\n const n = this.$s(e);\n return __PRIVATE_RemoteClientState.Es(n, t);\n }\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Gs(e, t) {\n const n = this.Ds.exec(e), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;\n return __PRIVATE_MutationMetadata.Es(new User(i), r, t);\n }\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ js(e, t) {\n const n = this.Cs.exec(e), r = Number(n[1]);\n return __PRIVATE_QueryTargetMetadata.Es(r, t);\n }\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ xs(e) {\n return __PRIVATE_SharedOnlineState.Es(e);\n }\n Js(e) {\n return JSON.parse(e);\n }\n async zs(e) {\n if (e.user.uid === this.currentUser.uid) return this.syncEngine.Zs(e.batchId, e.state, e.error);\n __PRIVATE_logDebug(\"SharedClientState\", `Ignoring mutation for non-active user ${e.user.uid}`);\n }\n Hs(e) {\n return this.syncEngine.Xs(e.targetId, e.state, e.error);\n }\n Us(e, t) {\n const n = t ? this.ps.insert(e, t) : this.ps.remove(e), r = this.Ns(this.ps), i = this.Ns(n), s = [], o = [];\n return i.forEach((e => {\n r.has(e) || s.push(e);\n })), r.forEach((e => {\n i.has(e) || o.push(e);\n })), this.syncEngine.eo(s, o).then((() => {\n this.ps = n;\n }));\n }\n Os(e) {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n this.ps.get(e.clientId) && this.onlineStateHandler(e.onlineState);\n }\n Ns(e) {\n let t = __PRIVATE_targetIdSet();\n return e.forEach(((e, n) => {\n t = t.unionWith(n.activeTargetIds);\n })), t;\n }\n}\n\nclass __PRIVATE_MemorySharedClientState {\n constructor() {\n this.no = new __PRIVATE_LocalClientState, this.ro = {}, this.onlineStateHandler = null, \n this.sequenceNumberHandler = null;\n }\n addPendingMutation(e) {\n // No op.\n }\n updateMutationState(e, t, n) {\n // No op.\n }\n addLocalQueryTarget(e) {\n return this.no.As(e), this.ro[e] || \"not-current\";\n }\n updateQueryState(e, t, n) {\n this.ro[e] = t;\n }\n removeLocalQueryTarget(e) {\n this.no.Rs(e);\n }\n isLocalQueryTarget(e) {\n return this.no.activeTargetIds.has(e);\n }\n clearQueryState(e) {\n delete this.ro[e];\n }\n getAllActiveQueryTargets() {\n return this.no.activeTargetIds;\n }\n isActiveQueryTarget(e) {\n return this.no.activeTargetIds.has(e);\n }\n start() {\n return this.no = new __PRIVATE_LocalClientState, Promise.resolve();\n }\n handleUserChange(e, t, n) {\n // No op.\n }\n setOnlineState(e) {\n // No op.\n }\n shutdown() {}\n writeSequenceNumber(e) {}\n notifyBundleLoaded(e) {\n // No op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_NoopConnectivityMonitor {\n io(e) {\n // No-op.\n }\n shutdown() {\n // No-op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nclass __PRIVATE_BrowserConnectivityMonitor {\n constructor() {\n this.so = () => this.oo(), this._o = () => this.ao(), this.uo = [], this.co();\n }\n io(e) {\n this.uo.push(e);\n }\n shutdown() {\n window.removeEventListener(\"online\", this.so), window.removeEventListener(\"offline\", this._o);\n }\n co() {\n window.addEventListener(\"online\", this.so), window.addEventListener(\"offline\", this._o);\n }\n oo() {\n __PRIVATE_logDebug(\"ConnectivityMonitor\", \"Network connectivity changed: AVAILABLE\");\n for (const e of this.uo) e(0 /* NetworkStatus.AVAILABLE */);\n }\n ao() {\n __PRIVATE_logDebug(\"ConnectivityMonitor\", \"Network connectivity changed: UNAVAILABLE\");\n for (const e of this.uo) e(1 /* NetworkStatus.UNAVAILABLE */);\n }\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static D() {\n return \"undefined\" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */ let Ae = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nfunction __PRIVATE_generateUniqueDebugId() {\n return null === Ae ? Ae = function __PRIVATE_generateInitialUniqueDebugId() {\n return 268435456 + Math.round(2147483648 * Math.random());\n }() : Ae++, \"0x\" + Ae.toString(16);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Re = {\n BatchGetDocuments: \"batchGet\",\n Commit: \"commit\",\n RunQuery: \"runQuery\",\n RunAggregationQuery: \"runAggregationQuery\"\n};\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nclass __PRIVATE_StreamBridge {\n constructor(e) {\n this.lo = e.lo, this.ho = e.ho;\n }\n Po(e) {\n this.Io = e;\n }\n To(e) {\n this.Eo = e;\n }\n onMessage(e) {\n this.Ao = e;\n }\n close() {\n this.ho();\n }\n send(e) {\n this.lo(e);\n }\n Ro() {\n this.Io();\n }\n Vo(e) {\n this.Eo(e);\n }\n mo(e) {\n this.Ao(e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ve = \"WebChannelConnection\";\n\nclass __PRIVATE_WebChannelConnection extends \n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nclass __PRIVATE_RestConnection {\n constructor(e) {\n this.databaseInfo = e, this.databaseId = e.databaseId;\n const t = e.ssl ? \"https\" : \"http\", n = encodeURIComponent(this.databaseId.projectId), r = encodeURIComponent(this.databaseId.database);\n this.fo = t + \"://\" + e.host, this.po = `projects/${n}/databases/${r}`, this.yo = \"(default)\" === this.databaseId.database ? `project_id=${n}` : `project_id=${n}&database_id=${r}`;\n }\n get wo() {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return !1;\n }\n So(e, t, n, r, i) {\n const s = __PRIVATE_generateUniqueDebugId(), o = this.bo(e, t.toUriEncodedString());\n __PRIVATE_logDebug(\"RestConnection\", `Sending RPC '${e}' ${s}:`, o, n);\n const _ = {\n \"google-cloud-resource-prefix\": this.po,\n \"x-goog-request-params\": this.yo\n };\n return this.Do(_, r, i), this.Co(e, o, _, n).then((t => (__PRIVATE_logDebug(\"RestConnection\", `Received RPC '${e}' ${s}: `, t), \n t)), (t => {\n throw __PRIVATE_logWarn(\"RestConnection\", `RPC '${e}' ${s} failed with error: `, t, \"url: \", o, \"request:\", n), \n t;\n }));\n }\n vo(e, t, n, r, i, s) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.So(e, t, n, r, i);\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */ Do(e, t, n) {\n e[\"X-Goog-Api-Client\"] = \n // SDK_VERSION is updated to different value at runtime depending on the entry point,\n // so we need to get its value when we need it in a function.\n function __PRIVATE_getGoogApiClientValue() {\n return \"gl-js/ fire/\" + S;\n }(), \n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n e[\"Content-Type\"] = \"text/plain\", this.databaseInfo.appId && (e[\"X-Firebase-GMPID\"] = this.databaseInfo.appId), \n t && t.headers.forEach(((t, n) => e[n] = t)), n && n.headers.forEach(((t, n) => e[n] = t));\n }\n bo(e, t) {\n const n = Re[e];\n return `${this.fo}/v1/${t}:${n}`;\n }\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */ terminate() {\n // No-op\n }\n} {\n constructor(e) {\n super(e), this.forceLongPolling = e.forceLongPolling, this.autoDetectLongPolling = e.autoDetectLongPolling, \n this.useFetchStreams = e.useFetchStreams, this.longPollingOptions = e.longPollingOptions;\n }\n Co(e, t, n, r) {\n const i = __PRIVATE_generateUniqueDebugId();\n return new Promise(((s, o) => {\n const _ = new _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.XhrIo;\n _.setWithCredentials(!0), _.listenOnce(_firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.EventType.COMPLETE, (() => {\n try {\n switch (_.getLastErrorCode()) {\n case _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.ErrorCode.NO_ERROR:\n const t = _.getResponseJson();\n __PRIVATE_logDebug(Ve, `XHR for RPC '${e}' ${i} received:`, JSON.stringify(t)), \n s(t);\n break;\n\n case _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.ErrorCode.TIMEOUT:\n __PRIVATE_logDebug(Ve, `RPC '${e}' ${i} timed out`), o(new FirestoreError(D.DEADLINE_EXCEEDED, \"Request time out\"));\n break;\n\n case _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.ErrorCode.HTTP_ERROR:\n const n = _.getStatus();\n if (__PRIVATE_logDebug(Ve, `RPC '${e}' ${i} failed with status:`, n, \"response text:\", _.getResponseText()), \n n > 0) {\n let e = _.getResponseJson();\n Array.isArray(e) && (e = e[0]);\n const t = null == e ? void 0 : e.error;\n if (t && t.status && t.message) {\n const e = function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e) {\n const t = e.toLowerCase().replace(/_/g, \"-\");\n return Object.values(D).indexOf(t) >= 0 ? t : D.UNKNOWN;\n }(t.status);\n o(new FirestoreError(e, t.message));\n } else o(new FirestoreError(D.UNKNOWN, \"Server responded with status \" + _.getStatus()));\n } else \n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n o(new FirestoreError(D.UNAVAILABLE, \"Connection failed.\"));\n break;\n\n default:\n fail();\n }\n } finally {\n __PRIVATE_logDebug(Ve, `RPC '${e}' ${i} completed.`);\n }\n }));\n const a = JSON.stringify(r);\n __PRIVATE_logDebug(Ve, `RPC '${e}' ${i} sending request:`, r), _.send(t, \"POST\", a, n, 15);\n }));\n }\n Fo(e, t, n) {\n const r = __PRIVATE_generateUniqueDebugId(), i = [ this.fo, \"/\", \"google.firestore.v1.Firestore\", \"/\", e, \"/channel\" ], s = (0,_firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.createWebChannelTransport)(), o = (0,_firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.getStatEventTarget)(), _ = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: \"gsessionid\",\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: !0,\n supportsCrossDomainXhr: !0,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 6e5\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n }, a = this.longPollingOptions.timeoutSeconds;\n void 0 !== a && (_.longPollingTimeout = Math.round(1e3 * a)), this.useFetchStreams && (_.useFetchStreams = !0), \n this.Do(_.initMessageHeaders, t, n), \n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n _.encodeInitMessageHeaders = !0;\n const u = i.join(\"\");\n __PRIVATE_logDebug(Ve, `Creating RPC '${e}' stream ${r}: ${u}`, _);\n const c = s.createWebChannel(u, _);\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let l = !1, h = !1;\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n const P = new __PRIVATE_StreamBridge({\n lo: t => {\n h ? __PRIVATE_logDebug(Ve, `Not sending because RPC '${e}' stream ${r} is closed:`, t) : (l || (__PRIVATE_logDebug(Ve, `Opening RPC '${e}' stream ${r} transport.`), \n c.open(), l = !0), __PRIVATE_logDebug(Ve, `RPC '${e}' stream ${r} sending:`, t), \n c.send(t));\n },\n ho: () => c.close()\n }), __PRIVATE_unguardedEventListen = (e, t, n) => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n e.listen(t, (e => {\n try {\n n(e);\n } catch (e) {\n setTimeout((() => {\n throw e;\n }), 0);\n }\n }));\n };\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n return __PRIVATE_unguardedEventListen(c, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.WebChannel.EventType.OPEN, (() => {\n h || __PRIVATE_logDebug(Ve, `RPC '${e}' stream ${r} transport opened.`);\n })), __PRIVATE_unguardedEventListen(c, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.WebChannel.EventType.CLOSE, (() => {\n h || (h = !0, __PRIVATE_logDebug(Ve, `RPC '${e}' stream ${r} transport closed`), \n P.Vo());\n })), __PRIVATE_unguardedEventListen(c, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.WebChannel.EventType.ERROR, (t => {\n h || (h = !0, __PRIVATE_logWarn(Ve, `RPC '${e}' stream ${r} transport errored:`, t), \n P.Vo(new FirestoreError(D.UNAVAILABLE, \"The operation could not be completed\")));\n })), __PRIVATE_unguardedEventListen(c, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.WebChannel.EventType.MESSAGE, (t => {\n var n;\n if (!h) {\n const i = t.data[0];\n __PRIVATE_hardAssert(!!i);\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const s = i, o = s.error || (null === (n = s[0]) || void 0 === n ? void 0 : n.error);\n if (o) {\n __PRIVATE_logDebug(Ve, `RPC '${e}' stream ${r} received error:`, o);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const t = o.status;\n let n = \n /**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\n function __PRIVATE_mapCodeFromRpcStatus(e) {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const t = ae[e];\n if (void 0 !== t) return __PRIVATE_mapCodeFromRpcCode(t);\n }(t), i = o.message;\n void 0 === n && (n = D.INTERNAL, i = \"Unknown error status: \" + t + \" with message \" + o.message), \n // Mark closed so no further events are propagated\n h = !0, P.Vo(new FirestoreError(n, i)), c.close();\n } else __PRIVATE_logDebug(Ve, `RPC '${e}' stream ${r} received:`, i), P.mo(i);\n }\n })), __PRIVATE_unguardedEventListen(o, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Event.STAT_EVENT, (t => {\n t.stat === _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Stat.PROXY ? __PRIVATE_logDebug(Ve, `RPC '${e}' stream ${r} detected buffering proxy`) : t.stat === _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__.Stat.NOPROXY && __PRIVATE_logDebug(Ve, `RPC '${e}' stream ${r} detected no buffering proxy`);\n })), setTimeout((() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n P.Ro();\n }), 0), P;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Initializes the WebChannelConnection for the browser. */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** The Platform's 'window' implementation or null if not available. */\nfunction __PRIVATE_getWindow() {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof window ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */ function getDocument() {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof document ? document : null;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_newSerializer(e) {\n return new JsonProtoSerializer(e, /* useProto3Json= */ !0);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nclass __PRIVATE_ExponentialBackoff {\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n e, \n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n t, \n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n n = 1e3\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */ , r = 1.5\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */ , i = 6e4) {\n this.oi = e, this.timerId = t, this.Mo = n, this.xo = r, this.Oo = i, this.No = 0, \n this.Lo = null, \n /** The last backoff attempt, as epoch milliseconds. */\n this.Bo = Date.now(), this.reset();\n }\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */ reset() {\n this.No = 0;\n }\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */ ko() {\n this.No = this.Oo;\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 */ qo(e) {\n // Cancel any pending backoff operation.\n this.cancel();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const t = Math.floor(this.No + this.Qo()), n = Math.max(0, Date.now() - this.Bo), r = Math.max(0, t - n);\n // Guard against lastAttemptTime being in the future due to a clock change.\n r > 0 && __PRIVATE_logDebug(\"ExponentialBackoff\", `Backing off for ${r} ms (base delay: ${this.No} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`), \n this.Lo = this.oi.enqueueAfterDelay(this.timerId, r, (() => (this.Bo = Date.now(), \n e()))), \n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.No *= this.xo, this.No < this.Mo && (this.No = this.Mo), this.No > this.Oo && (this.No = this.Oo);\n }\n Ko() {\n null !== this.Lo && (this.Lo.skipDelay(), this.Lo = null);\n }\n cancel() {\n null !== this.Lo && (this.Lo.cancel(), this.Lo = null);\n }\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ Qo() {\n return (Math.random() - .5) * this.No;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nclass __PRIVATE_PersistentStream {\n constructor(e, t, n, r, i, s, o, _) {\n this.oi = e, this.$o = n, this.Uo = r, this.connection = i, this.authCredentialsProvider = s, \n this.appCheckCredentialsProvider = o, this.listener = _, this.state = 0 /* PersistentStreamState.Initial */ , \n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n this.Wo = 0, this.Go = null, this.zo = null, this.stream = null, this.jo = new __PRIVATE_ExponentialBackoff(e, t);\n }\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */ Ho() {\n return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.Jo();\n }\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */ Jo() {\n return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;\n }\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */ start() {\n 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Yo();\n }\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */ async stop() {\n this.Ho() && await this.close(0 /* PersistentStreamState.Initial */);\n }\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */ Zo() {\n this.state = 0 /* PersistentStreamState.Initial */ , this.jo.reset();\n }\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */ Xo() {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n this.Jo() && null === this.Go && (this.Go = this.oi.enqueueAfterDelay(this.$o, 6e4, (() => this.e_())));\n }\n /** Sends a message to the underlying stream. */ t_(e) {\n this.n_(), this.stream.send(e);\n }\n /** Called by the idle timer when the stream should close due to inactivity. */ async e_() {\n if (this.Jo()) \n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(0 /* PersistentStreamState.Initial */);\n }\n /** Marks the stream as active again. */ n_() {\n this.Go && (this.Go.cancel(), this.Go = null);\n }\n /** Cancels the health check delayed operation. */ r_() {\n this.zo && (this.zo.cancel(), this.zo = null);\n }\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */ async close(e, t) {\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.n_(), this.r_(), this.jo.cancel(), \n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.Wo++, 4 /* PersistentStreamState.Error */ !== e ? \n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.jo.reset() : t && t.code === D.RESOURCE_EXHAUSTED ? (\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n __PRIVATE_logError(t.toString()), __PRIVATE_logError(\"Using maximum backoff delay to prevent overloading the backend.\"), \n this.jo.ko()) : t && t.code === D.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), \n // Clean up the underlying stream because we are no longer interested in events.\n null !== this.stream && (this.i_(), this.stream.close(), this.stream = null), \n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = e, \n // Notify the listener that the stream closed.\n await this.listener.To(t);\n }\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */ i_() {}\n auth() {\n this.state = 1 /* PersistentStreamState.Starting */;\n const e = this.s_(this.Wo), t = this.Wo;\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([e, n]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n this.Wo === t && \n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.o_(e, n);\n }), (t => {\n e((() => {\n const e = new FirestoreError(D.UNKNOWN, \"Fetching auth token failed: \" + t.message);\n return this.__(e);\n }));\n }));\n }\n o_(e, t) {\n const n = this.s_(this.Wo);\n this.stream = this.a_(e, t), this.stream.Po((() => {\n n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.zo = this.oi.enqueueAfterDelay(this.Uo, 1e4, (() => (this.Jo() && (this.state = 3 /* PersistentStreamState.Healthy */), \n Promise.resolve()))), this.listener.Po())));\n })), this.stream.To((e => {\n n((() => this.__(e)));\n })), this.stream.onMessage((e => {\n n((() => this.onMessage(e)));\n }));\n }\n Yo() {\n this.state = 5 /* PersistentStreamState.Backoff */ , this.jo.qo((async () => {\n this.state = 0 /* PersistentStreamState.Initial */ , this.start();\n }));\n }\n // Visible for tests\n __(e) {\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return __PRIVATE_logDebug(\"PersistentStream\", `close with error: ${e}`), this.stream = null, \n this.close(4 /* PersistentStreamState.Error */ , e);\n }\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */ s_(e) {\n return t => {\n this.oi.enqueueAndForget((() => this.Wo === e ? t() : (__PRIVATE_logDebug(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), \n Promise.resolve())));\n };\n }\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */ class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream {\n constructor(e, t, n, r, i, s) {\n super(e, \"listen_stream_connection_backoff\" /* TimerId.ListenStreamConnectionBackoff */ , \"listen_stream_idle\" /* TimerId.ListenStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , t, n, r, s), \n this.serializer = i;\n }\n a_(e, t) {\n return this.connection.Fo(\"Listen\", e, t);\n }\n onMessage(e) {\n // A successful response means the stream is healthy\n this.jo.reset();\n const t = __PRIVATE_fromWatchChange(this.serializer, e), n = function __PRIVATE_versionFromListenResponse(e) {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!(\"targetChange\" in e)) return SnapshotVersion.min();\n const t = e.targetChange;\n return t.targetIds && t.targetIds.length ? SnapshotVersion.min() : t.readTime ? __PRIVATE_fromVersion(t.readTime) : SnapshotVersion.min();\n }(e);\n return this.listener.u_(t, n);\n }\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */ c_(e) {\n const t = {};\n t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.addTarget = function __PRIVATE_toTarget(e, t) {\n let n;\n const r = t.target;\n if (n = __PRIVATE_targetIsDocumentTarget(r) ? {\n documents: __PRIVATE_toDocumentsTarget(e, r)\n } : {\n query: __PRIVATE_toQueryTarget(e, r).ut\n }, n.targetId = t.targetId, t.resumeToken.approximateByteSize() > 0) {\n n.resumeToken = __PRIVATE_toBytes(e, t.resumeToken);\n const r = __PRIVATE_toInt32Proto(e, t.expectedCount);\n null !== r && (n.expectedCount = r);\n } else if (t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n n.readTime = toTimestamp(e, t.snapshotVersion.toTimestamp());\n const r = __PRIVATE_toInt32Proto(e, t.expectedCount);\n null !== r && (n.expectedCount = r);\n }\n return n;\n }(this.serializer, e);\n const n = __PRIVATE_toListenRequestLabels(this.serializer, e);\n n && (t.labels = n), this.t_(t);\n }\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */ l_(e) {\n const t = {};\n t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.removeTarget = e, \n this.t_(t);\n }\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */ class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream {\n constructor(e, t, n, r, i, s) {\n super(e, \"write_stream_connection_backoff\" /* TimerId.WriteStreamConnectionBackoff */ , \"write_stream_idle\" /* TimerId.WriteStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , t, n, r, s), \n this.serializer = i, this.h_ = !1;\n }\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */ get P_() {\n return this.h_;\n }\n // Override of PersistentStream.start\n start() {\n this.h_ = !1, this.lastStreamToken = void 0, super.start();\n }\n i_() {\n this.h_ && this.I_([]);\n }\n a_(e, t) {\n return this.connection.Fo(\"Write\", e, t);\n }\n onMessage(e) {\n if (\n // Always capture the last stream token.\n __PRIVATE_hardAssert(!!e.streamToken), this.lastStreamToken = e.streamToken, this.h_) {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.jo.reset();\n const t = __PRIVATE_fromWriteResults(e.writeResults, e.commitTime), n = __PRIVATE_fromVersion(e.commitTime);\n return this.listener.T_(n, t);\n }\n // The first response is always the handshake response\n return __PRIVATE_hardAssert(!e.writeResults || 0 === e.writeResults.length), this.h_ = !0, \n this.listener.E_();\n }\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */ d_() {\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const e = {};\n e.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.t_(e);\n }\n /** Sends a group of mutations to the Firestore backend to apply. */ I_(e) {\n const t = {\n streamToken: this.lastStreamToken,\n writes: e.map((e => toMutation(this.serializer, e)))\n };\n this.t_(t);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass __PRIVATE_DatastoreImpl extends class Datastore {} {\n constructor(e, t, n, r) {\n super(), this.authCredentials = e, this.appCheckCredentials = t, this.connection = n, \n this.serializer = r, this.A_ = !1;\n }\n R_() {\n if (this.A_) throw new FirestoreError(D.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n /** Invokes the provided RPC with auth and AppCheck tokens. */ So(e, t, n, r) {\n return this.R_(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.So(e, __PRIVATE_toResourcePath(t, n), r, i, s))).catch((e => {\n throw \"FirebaseError\" === e.name ? (e.code === D.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(D.UNKNOWN, e.toString());\n }));\n }\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ vo(e, t, n, r, i) {\n return this.R_(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.vo(e, __PRIVATE_toResourcePath(t, n), r, s, o, i))).catch((e => {\n throw \"FirebaseError\" === e.name ? (e.code === D.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(D.UNKNOWN, e.toString());\n }));\n }\n terminate() {\n this.A_ = !0, this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nasync function __PRIVATE_invokeRunAggregationQueryRpc(e, t, n) {\n var r;\n const i = __PRIVATE_debugCast(e), {request: s, V_: o, parent: _} = function __PRIVATE_toRunAggregationQueryRequest(e, t, n) {\n const {ut: r, parent: i} = __PRIVATE_toQueryTarget(e, t), s = {}, o = [];\n let _ = 0;\n return n.forEach((e => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const t = \"aggregate_\" + _++;\n s[t] = e.alias, \"count\" === e.aggregateType ? o.push({\n alias: t,\n count: {}\n }) : \"avg\" === e.aggregateType ? o.push({\n alias: t,\n avg: {\n field: __PRIVATE_toFieldPathReference(e.fieldPath)\n }\n }) : \"sum\" === e.aggregateType && o.push({\n alias: t,\n sum: {\n field: __PRIVATE_toFieldPathReference(e.fieldPath)\n }\n });\n })), {\n request: {\n structuredAggregationQuery: {\n aggregations: o,\n structuredQuery: r.structuredQuery\n },\n parent: r.parent\n },\n V_: s,\n parent: i\n };\n }(i.serializer, function __PRIVATE_queryToAggregateTarget(e) {\n const t = __PRIVATE_debugCast(e);\n return t.Pe || (\n // Do not include implicit order-bys for aggregate queries.\n t.Pe = __PRIVATE__queryToTarget(t, e.explicitOrderBy)), t.Pe;\n }(t), n);\n i.connection.wo || delete s.parent;\n const a = (await i.vo(\"RunAggregationQuery\", i.serializer.databaseId, _, s, \n /*expectedResponseCount=*/ 1)).filter((e => !!e.result));\n // Omit RunAggregationQueryResponse that only contain readTimes.\n __PRIVATE_hardAssert(1 === a.length);\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const u = null === (r = a[0].result) || void 0 === r ? void 0 : r.aggregateFields;\n return Object.keys(u).reduce(((e, t) => (e[o[t]] = u[t], e)), {});\n}\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nclass __PRIVATE_OnlineStateTracker {\n constructor(e, t) {\n this.asyncQueue = e, this.onlineStateHandler = t, \n /** The current OnlineState. */\n this.state = \"Unknown\" /* OnlineState.Unknown */ , \n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n this.m_ = 0, \n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n this.f_ = null, \n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n this.g_ = !0;\n }\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */ p_() {\n 0 === this.m_ && (this.y_(\"Unknown\" /* OnlineState.Unknown */), this.f_ = this.asyncQueue.enqueueAfterDelay(\"online_state_timeout\" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this.f_ = null, \n this.w_(\"Backend didn't respond within 10 seconds.\"), this.y_(\"Offline\" /* OnlineState.Offline */), \n Promise.resolve()))));\n }\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */ S_(e) {\n \"Online\" /* OnlineState.Online */ === this.state ? this.y_(\"Unknown\" /* OnlineState.Unknown */) : (this.m_++, \n this.m_ >= 1 && (this.b_(), this.w_(`Connection failed 1 times. Most recent error: ${e.toString()}`), \n this.y_(\"Offline\" /* OnlineState.Offline */)));\n }\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */ set(e) {\n this.b_(), this.m_ = 0, \"Online\" /* OnlineState.Online */ === e && (\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.g_ = !1), this.y_(e);\n }\n y_(e) {\n e !== this.state && (this.state = e, this.onlineStateHandler(e));\n }\n w_(e) {\n const t = `Could not reach Cloud Firestore backend. ${e}\\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;\n this.g_ ? (__PRIVATE_logError(t), this.g_ = !1) : __PRIVATE_logDebug(\"OnlineStateTracker\", t);\n }\n b_() {\n null !== this.f_ && (this.f_.cancel(), this.f_ = null);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_RemoteStoreImpl {\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n e, \n /** The client-side proxy for interacting with the backend. */\n t, n, r, i) {\n this.localStore = e, this.datastore = t, this.asyncQueue = n, this.remoteSyncer = {}, \n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n this.D_ = [], \n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n this.C_ = new Map, \n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n this.v_ = new Set, \n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n this.F_ = [], this.M_ = i, this.M_.io((e => {\n n.enqueueAndForget((async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(\"RemoteStore\", \"Restarting streams for network reachability change.\"), \n await async function __PRIVATE_restartNetwork(e) {\n const t = __PRIVATE_debugCast(e);\n t.v_.add(4 /* OfflineCause.ConnectivityChange */), await __PRIVATE_disableNetworkInternal(t), \n t.x_.set(\"Unknown\" /* OnlineState.Unknown */), t.v_.delete(4 /* OfflineCause.ConnectivityChange */), \n await __PRIVATE_enableNetworkInternal(t);\n }(this));\n }));\n })), this.x_ = new __PRIVATE_OnlineStateTracker(n, r);\n }\n}\n\nasync function __PRIVATE_enableNetworkInternal(e) {\n if (__PRIVATE_canUseNetwork(e)) for (const t of e.F_) await t(/* enabled= */ !0);\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */ async function __PRIVATE_disableNetworkInternal(e) {\n for (const t of e.F_) await t(/* enabled= */ !1);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nfunction __PRIVATE_remoteStoreListen(e, t) {\n const n = __PRIVATE_debugCast(e);\n n.C_.has(t.targetId) || (\n // Mark this as something the client is currently listening for.\n n.C_.set(t.targetId, t), __PRIVATE_shouldStartWatchStream(n) ? \n // The listen will be sent in onWatchStreamOpen\n __PRIVATE_startWatchStream(n) : __PRIVATE_ensureWatchStream(n).Jo() && __PRIVATE_sendWatchRequest(n, t));\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */ function __PRIVATE_remoteStoreUnlisten(e, t) {\n const n = __PRIVATE_debugCast(e), r = __PRIVATE_ensureWatchStream(n);\n n.C_.delete(t), r.Jo() && __PRIVATE_sendUnwatchRequest(n, t), 0 === n.C_.size && (r.Jo() ? r.Xo() : __PRIVATE_canUseNetwork(n) && \n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n n.x_.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */ function __PRIVATE_sendWatchRequest(e, t) {\n if (e.O_.Oe(t.targetId), t.resumeToken.approximateByteSize() > 0 || t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n const n = e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;\n t = t.withExpectedCount(n);\n }\n __PRIVATE_ensureWatchStream(e).c_(t);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */ function __PRIVATE_sendUnwatchRequest(e, t) {\n e.O_.Oe(t), __PRIVATE_ensureWatchStream(e).l_(t);\n}\n\nfunction __PRIVATE_startWatchStream(e) {\n e.O_ = new __PRIVATE_WatchChangeAggregator({\n getRemoteKeysForTarget: t => e.remoteSyncer.getRemoteKeysForTarget(t),\n _t: t => e.C_.get(t) || null,\n nt: () => e.datastore.serializer.databaseId\n }), __PRIVATE_ensureWatchStream(e).start(), e.x_.p_();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */ function __PRIVATE_shouldStartWatchStream(e) {\n return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWatchStream(e).Ho() && e.C_.size > 0;\n}\n\nfunction __PRIVATE_canUseNetwork(e) {\n return 0 === __PRIVATE_debugCast(e).v_.size;\n}\n\nfunction __PRIVATE_cleanUpWatchStreamState(e) {\n e.O_ = void 0;\n}\n\nasync function __PRIVATE_onWatchStreamOpen(e) {\n e.C_.forEach(((t, n) => {\n __PRIVATE_sendWatchRequest(e, t);\n }));\n}\n\nasync function __PRIVATE_onWatchStreamClose(e, t) {\n __PRIVATE_cleanUpWatchStreamState(e), \n // If we still need the watch stream, retry the connection.\n __PRIVATE_shouldStartWatchStream(e) ? (e.x_.S_(t), __PRIVATE_startWatchStream(e)) : \n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n e.x_.set(\"Unknown\" /* OnlineState.Unknown */);\n}\n\nasync function __PRIVATE_onWatchStreamChange(e, t, n) {\n if (\n // Mark the client as online since we got a message from the server\n e.x_.set(\"Online\" /* OnlineState.Online */), t instanceof __PRIVATE_WatchTargetChange && 2 /* WatchTargetChangeState.Removed */ === t.state && t.cause) \n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await \n /** Handles an error on a target */\n async function __PRIVATE_handleTargetError(e, t) {\n const n = t.cause;\n for (const r of t.targetIds) \n // A watched target might have been removed already.\n e.C_.has(r) && (await e.remoteSyncer.rejectListen(r, n), e.C_.delete(r), e.O_.removeTarget(r));\n }\n /**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */ (e, t);\n } catch (n) {\n __PRIVATE_logDebug(\"RemoteStore\", \"Failed to remove targets %s: %s \", t.targetIds.join(\",\"), n), \n await __PRIVATE_disableNetworkUntilRecovery(e, n);\n } else if (t instanceof __PRIVATE_DocumentWatchChange ? e.O_.$e(t) : t instanceof __PRIVATE_ExistenceFilterChange ? e.O_.Je(t) : e.O_.Ge(t), \n !n.isEqual(SnapshotVersion.min())) try {\n const t = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore);\n n.compareTo(t) >= 0 && \n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await \n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n function __PRIVATE_raiseWatchSnapshot(e, t) {\n const n = e.O_.it(t);\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n return n.targetChanges.forEach(((n, r) => {\n if (n.resumeToken.approximateByteSize() > 0) {\n const i = e.C_.get(r);\n // A watched target might have been removed already.\n i && e.C_.set(r, i.withResumeToken(n.resumeToken, t));\n }\n })), \n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n n.targetMismatches.forEach(((t, n) => {\n const r = e.C_.get(t);\n if (!r) \n // A watched target might have been removed already.\n return;\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n e.C_.set(t, r.withResumeToken(ByteString.EMPTY_BYTE_STRING, r.snapshotVersion)), \n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n __PRIVATE_sendUnwatchRequest(e, t);\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const i = new TargetData(r.target, t, n, r.sequenceNumber);\n __PRIVATE_sendWatchRequest(e, i);\n })), e.remoteSyncer.applyRemoteEvent(n);\n }(e, n);\n } catch (t) {\n __PRIVATE_logDebug(\"RemoteStore\", \"Failed to raise snapshot:\", t), await __PRIVATE_disableNetworkUntilRecovery(e, t);\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */ async function __PRIVATE_disableNetworkUntilRecovery(e, t, n) {\n if (!__PRIVATE_isIndexedDbTransactionError(t)) throw t;\n e.v_.add(1 /* OfflineCause.IndexedDbFailed */), \n // Disable network and raise offline snapshots\n await __PRIVATE_disableNetworkInternal(e), e.x_.set(\"Offline\" /* OnlineState.Offline */), \n n || (\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n n = () => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)), \n // Probe IndexedDB periodically and re-enable network\n e.asyncQueue.enqueueRetryable((async () => {\n __PRIVATE_logDebug(\"RemoteStore\", \"Retrying IndexedDB access\"), await n(), e.v_.delete(1 /* OfflineCause.IndexedDbFailed */), \n await __PRIVATE_enableNetworkInternal(e);\n }));\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */ function __PRIVATE_executeWithRecovery(e, t) {\n return t().catch((n => __PRIVATE_disableNetworkUntilRecovery(e, n, t)));\n}\n\nasync function __PRIVATE_fillWritePipeline(e) {\n const t = __PRIVATE_debugCast(e), n = __PRIVATE_ensureWriteStream(t);\n let r = t.D_.length > 0 ? t.D_[t.D_.length - 1].batchId : -1;\n for (;__PRIVATE_canAddToWritePipeline(t); ) try {\n const e = await __PRIVATE_localStoreGetNextMutationBatch(t.localStore, r);\n if (null === e) {\n 0 === t.D_.length && n.Xo();\n break;\n }\n r = e.batchId, __PRIVATE_addToWritePipeline(t, e);\n } catch (e) {\n await __PRIVATE_disableNetworkUntilRecovery(t, e);\n }\n __PRIVATE_shouldStartWriteStream(t) && __PRIVATE_startWriteStream(t);\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */ function __PRIVATE_canAddToWritePipeline(e) {\n return __PRIVATE_canUseNetwork(e) && e.D_.length < 10;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */ function __PRIVATE_addToWritePipeline(e, t) {\n e.D_.push(t);\n const n = __PRIVATE_ensureWriteStream(e);\n n.Jo() && n.P_ && n.I_(t.mutations);\n}\n\nfunction __PRIVATE_shouldStartWriteStream(e) {\n return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWriteStream(e).Ho() && e.D_.length > 0;\n}\n\nfunction __PRIVATE_startWriteStream(e) {\n __PRIVATE_ensureWriteStream(e).start();\n}\n\nasync function __PRIVATE_onWriteStreamOpen(e) {\n __PRIVATE_ensureWriteStream(e).d_();\n}\n\nasync function __PRIVATE_onWriteHandshakeComplete(e) {\n const t = __PRIVATE_ensureWriteStream(e);\n // Send the write pipeline now that the stream is established.\n for (const n of e.D_) t.I_(n.mutations);\n}\n\nasync function __PRIVATE_onMutationResult(e, t, n) {\n const r = e.D_.shift(), i = MutationBatchResult.from(r, t, n);\n await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.applySuccessfulWrite(i))), \n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await __PRIVATE_fillWritePipeline(e);\n}\n\nasync function __PRIVATE_onWriteStreamClose(e, t) {\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n t && __PRIVATE_ensureWriteStream(e).P_ && \n // This error affects the actual write.\n await async function __PRIVATE_handleWriteError(e, t) {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (function __PRIVATE_isPermanentWriteError(e) {\n return __PRIVATE_isPermanentError(e) && e !== D.ABORTED;\n }(t.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const n = e.D_.shift();\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n __PRIVATE_ensureWriteStream(e).Zo(), await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.rejectFailedWrite(n.batchId, t))), \n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await __PRIVATE_fillWritePipeline(e);\n }\n }(e, t), \n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n __PRIVATE_shouldStartWriteStream(e) && __PRIVATE_startWriteStream(e);\n}\n\nasync function __PRIVATE_remoteStoreHandleCredentialChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n n.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(\"RemoteStore\", \"RemoteStore received new credentials\");\n const r = __PRIVATE_canUseNetwork(n);\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n n.v_.add(3 /* OfflineCause.CredentialChange */), await __PRIVATE_disableNetworkInternal(n), \n r && \n // Don't set the network status to Unknown if we are offline.\n n.x_.set(\"Unknown\" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(t), \n n.v_.delete(3 /* OfflineCause.CredentialChange */), await __PRIVATE_enableNetworkInternal(n);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */ async function __PRIVATE_remoteStoreApplyPrimaryState(e, t) {\n const n = __PRIVATE_debugCast(e);\n t ? (n.v_.delete(2 /* OfflineCause.IsSecondary */), await __PRIVATE_enableNetworkInternal(n)) : t || (n.v_.add(2 /* OfflineCause.IsSecondary */), \n await __PRIVATE_disableNetworkInternal(n), n.x_.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function __PRIVATE_ensureWatchStream(e) {\n return e.N_ || (\n // Create stream (but note that it is not started yet).\n e.N_ = function __PRIVATE_newPersistentWatchStream(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n return r.R_(), new __PRIVATE_PersistentListenStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (e.datastore, e.asyncQueue, {\n Po: __PRIVATE_onWatchStreamOpen.bind(null, e),\n To: __PRIVATE_onWatchStreamClose.bind(null, e),\n u_: __PRIVATE_onWatchStreamChange.bind(null, e)\n }), e.F_.push((async t => {\n t ? (e.N_.Zo(), __PRIVATE_shouldStartWatchStream(e) ? __PRIVATE_startWatchStream(e) : e.x_.set(\"Unknown\" /* OnlineState.Unknown */)) : (await e.N_.stop(), \n __PRIVATE_cleanUpWatchStreamState(e));\n }))), e.N_;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function __PRIVATE_ensureWriteStream(e) {\n return e.L_ || (\n // Create stream (but note that it is not started yet).\n e.L_ = function __PRIVATE_newPersistentWriteStream(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n return r.R_(), new __PRIVATE_PersistentWriteStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);\n }(e.datastore, e.asyncQueue, {\n Po: __PRIVATE_onWriteStreamOpen.bind(null, e),\n To: __PRIVATE_onWriteStreamClose.bind(null, e),\n E_: __PRIVATE_onWriteHandshakeComplete.bind(null, e),\n T_: __PRIVATE_onMutationResult.bind(null, e)\n }), e.F_.push((async t => {\n t ? (e.L_.Zo(), \n // This will start the write stream if necessary.\n await __PRIVATE_fillWritePipeline(e)) : (await e.L_.stop(), e.D_.length > 0 && (__PRIVATE_logDebug(\"RemoteStore\", `Stopping write stream with ${e.D_.length} pending writes`), \n e.D_ = []));\n }))), e.L_;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nclass DelayedOperation {\n constructor(e, t, n, r, i) {\n this.asyncQueue = e, this.timerId = t, this.targetTimeMs = n, this.op = r, this.removalCallback = i, \n this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), \n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch((e => {}));\n }\n get promise() {\n return this.deferred.promise;\n }\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */ static createAndSchedule(e, t, n, r, i) {\n const s = Date.now() + n, o = new DelayedOperation(e, t, s, r, i);\n return o.start(n), o;\n }\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */ start(e) {\n this.timerHandle = setTimeout((() => this.handleDelayElapsed()), e);\n }\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */ skipDelay() {\n return this.handleDelayElapsed();\n }\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */ cancel(e) {\n null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(D.CANCELLED, \"Operation cancelled\" + (e ? \": \" + e : \"\"))));\n }\n handleDelayElapsed() {\n this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), \n this.op().then((e => this.deferred.resolve(e)))) : Promise.resolve()));\n }\n clearTimeout() {\n null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), \n this.timerHandle = null);\n }\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */ function __PRIVATE_wrapInUserErrorIfRecoverable(e, t) {\n if (__PRIVATE_logError(\"AsyncQueue\", `${t}: ${e}`), __PRIVATE_isIndexedDbTransactionError(e)) return new FirestoreError(D.UNAVAILABLE, `${t}: ${e}`);\n throw e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */ class DocumentSet {\n /** The default ordering is by key if the comparator is omitted */\n constructor(e) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n this.comparator = e ? (t, n) => e(t, n) || DocumentKey.comparator(t.key, n.key) : (e, t) => DocumentKey.comparator(e.key, t.key), \n this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */ static emptySet(e) {\n return new DocumentSet(e.comparator);\n }\n has(e) {\n return null != this.keyedMap.get(e);\n }\n get(e) {\n return this.keyedMap.get(e);\n }\n first() {\n return this.sortedSet.minKey();\n }\n last() {\n return this.sortedSet.maxKey();\n }\n isEmpty() {\n return this.sortedSet.isEmpty();\n }\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */ indexOf(e) {\n const t = this.keyedMap.get(e);\n return t ? this.sortedSet.indexOf(t) : -1;\n }\n get size() {\n return this.sortedSet.size;\n }\n /** Iterates documents in order defined by \"comparator\" */ forEach(e) {\n this.sortedSet.inorderTraversal(((t, n) => (e(t), !1)));\n }\n /** Inserts or updates a document with the same key */ add(e) {\n // First remove the element if we have it.\n const t = this.delete(e.key);\n return t.copy(t.keyedMap.insert(e.key, e), t.sortedSet.insert(e, null));\n }\n /** Deletes a document with a given key */ delete(e) {\n const t = this.get(e);\n return t ? this.copy(this.keyedMap.remove(e), this.sortedSet.remove(t)) : this;\n }\n isEqual(e) {\n if (!(e instanceof DocumentSet)) return !1;\n if (this.size !== e.size) return !1;\n const t = this.sortedSet.getIterator(), n = e.sortedSet.getIterator();\n for (;t.hasNext(); ) {\n const e = t.getNext().key, r = n.getNext().key;\n if (!e.isEqual(r)) return !1;\n }\n return !0;\n }\n toString() {\n const e = [];\n return this.forEach((t => {\n e.push(t.toString());\n })), 0 === e.length ? \"DocumentSet ()\" : \"DocumentSet (\\n \" + e.join(\" \\n\") + \"\\n)\";\n }\n copy(e, t) {\n const n = new DocumentSet;\n return n.comparator = this.comparator, n.keyedMap = e, n.sortedSet = t, n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */ class __PRIVATE_DocumentChangeSet {\n constructor() {\n this.B_ = new SortedMap(DocumentKey.comparator);\n }\n track(e) {\n const t = e.doc.key, n = this.B_.get(t);\n n ? \n // Merge the new change with the existing change.\n 0 /* ChangeType.Added */ !== e.type && 3 /* ChangeType.Metadata */ === n.type ? this.B_ = this.B_.insert(t, e) : 3 /* ChangeType.Metadata */ === e.type && 1 /* ChangeType.Removed */ !== n.type ? this.B_ = this.B_.insert(t, {\n type: n.type,\n doc: e.doc\n }) : 2 /* ChangeType.Modified */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.B_ = this.B_.insert(t, {\n type: 2 /* ChangeType.Modified */ ,\n doc: e.doc\n }) : 2 /* ChangeType.Modified */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.B_ = this.B_.insert(t, {\n type: 0 /* ChangeType.Added */ ,\n doc: e.doc\n }) : 1 /* ChangeType.Removed */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.B_ = this.B_.remove(t) : 1 /* ChangeType.Removed */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.B_ = this.B_.insert(t, {\n type: 1 /* ChangeType.Removed */ ,\n doc: n.doc\n }) : 0 /* ChangeType.Added */ === e.type && 1 /* ChangeType.Removed */ === n.type ? this.B_ = this.B_.insert(t, {\n type: 2 /* ChangeType.Modified */ ,\n doc: e.doc\n }) : \n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail() : this.B_ = this.B_.insert(t, e);\n }\n k_() {\n const e = [];\n return this.B_.inorderTraversal(((t, n) => {\n e.push(n);\n })), e;\n }\n}\n\nclass ViewSnapshot {\n constructor(e, t, n, r, i, s, o, _, a) {\n this.query = e, this.docs = t, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i, \n this.fromCache = s, this.syncStateChanged = o, this.excludesMetadataChanges = _, \n this.hasCachedResults = a;\n }\n /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(e, t, n, r, i) {\n const s = [];\n return t.forEach((e => {\n s.push({\n type: 0 /* ChangeType.Added */ ,\n doc: e\n });\n })), new ViewSnapshot(e, t, DocumentSet.emptySet(t), s, n, r, \n /* syncStateChanged= */ !0, \n /* excludesMetadataChanges= */ !1, i);\n }\n get hasPendingWrites() {\n return !this.mutatedKeys.isEmpty();\n }\n isEqual(e) {\n if (!(this.fromCache === e.fromCache && this.hasCachedResults === e.hasCachedResults && this.syncStateChanged === e.syncStateChanged && this.mutatedKeys.isEqual(e.mutatedKeys) && __PRIVATE_queryEquals(this.query, e.query) && this.docs.isEqual(e.docs) && this.oldDocs.isEqual(e.oldDocs))) return !1;\n const t = this.docChanges, n = e.docChanges;\n if (t.length !== n.length) return !1;\n for (let e = 0; e < t.length; e++) if (t[e].type !== n[e].type || !t[e].doc.isEqual(n[e].doc)) return !1;\n return !0;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */ class __PRIVATE_QueryListenersInfo {\n constructor() {\n this.q_ = void 0, this.Q_ = [];\n }\n // Helper methods that checks if the query has listeners that listening to remote store\n K_() {\n return this.Q_.some((e => e.U_()));\n }\n}\n\nclass __PRIVATE_EventManagerImpl {\n constructor() {\n this.queries = new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals), \n this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , this.W_ = new Set;\n }\n}\n\nasync function __PRIVATE_eventManagerListen(e, t) {\n const n = __PRIVATE_debugCast(e);\n let r = 3 /* ListenerSetupAction.NoActionRequired */;\n const i = t.query;\n let s = n.queries.get(i);\n s ? !s.K_() && t.U_() && (\n // Query has been listening to local cache, and tries to add a new listener sourced from watch.\n r = 2 /* ListenerSetupAction.RequireWatchConnectionOnly */) : (s = new __PRIVATE_QueryListenersInfo, \n r = t.U_() ? 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : 1 /* ListenerSetupAction.InitializeLocalListenOnly */);\n try {\n switch (r) {\n case 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ :\n s.q_ = await n.onListen(i, \n /** enableRemoteListen= */ !0);\n break;\n\n case 1 /* ListenerSetupAction.InitializeLocalListenOnly */ :\n s.q_ = await n.onListen(i, \n /** enableRemoteListen= */ !1);\n break;\n\n case 2 /* ListenerSetupAction.RequireWatchConnectionOnly */ :\n await n.onFirstRemoteStoreListen(i);\n }\n } catch (e) {\n const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Initialization of query '${__PRIVATE_stringifyQuery(t.query)}' failed`);\n return void t.onError(n);\n }\n if (n.queries.set(i, s), s.Q_.push(t), \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n t.G_(n.onlineState), s.q_) {\n t.z_(s.q_) && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n }\n}\n\nasync function __PRIVATE_eventManagerUnlisten(e, t) {\n const n = __PRIVATE_debugCast(e), r = t.query;\n let i = 3 /* ListenerRemovalAction.NoActionRequired */;\n const s = n.queries.get(r);\n if (s) {\n const e = s.Q_.indexOf(t);\n e >= 0 && (s.Q_.splice(e, 1), 0 === s.Q_.length ? i = t.U_() ? 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : !s.K_() && t.U_() && (\n // The removed listener is the last one that sourced from watch.\n i = 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */));\n }\n switch (i) {\n case 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ :\n return n.queries.delete(r), n.onUnlisten(r, \n /** disableRemoteListen= */ !0);\n\n case 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ :\n return n.queries.delete(r), n.onUnlisten(r, \n /** disableRemoteListen= */ !1);\n\n case 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */ :\n return n.onLastRemoteStoreUnlisten(r);\n\n default:\n return;\n }\n}\n\nfunction __PRIVATE_eventManagerOnWatchChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n let r = !1;\n for (const e of t) {\n const t = e.query, i = n.queries.get(t);\n if (i) {\n for (const t of i.Q_) t.z_(e) && (r = !0);\n i.q_ = e;\n }\n }\n r && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n}\n\nfunction __PRIVATE_eventManagerOnWatchError(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = r.queries.get(t);\n if (i) for (const e of i.Q_) e.onError(n);\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n r.queries.delete(t);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction __PRIVATE_raiseSnapshotsInSyncEvent(e) {\n e.W_.forEach((e => {\n e.next();\n }));\n}\n\nvar me, fe;\n\n/** Listen to both cache and server changes */\n(fe = me || (me = {})).j_ = \"default\", \n/** Listen to changes in cache only */\nfe.Cache = \"cache\";\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nclass __PRIVATE_QueryListener {\n constructor(e, t, n) {\n this.query = e, this.H_ = t, \n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n this.J_ = !1, this.Y_ = null, this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.options = n || {};\n }\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */ z_(e) {\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const t = [];\n for (const n of e.docChanges) 3 /* ChangeType.Metadata */ !== n.type && t.push(n);\n e = new ViewSnapshot(e.query, e.docs, e.oldDocs, t, e.mutatedKeys, e.fromCache, e.syncStateChanged, \n /* excludesMetadataChanges= */ !0, e.hasCachedResults);\n }\n let t = !1;\n return this.J_ ? this.Z_(e) && (this.H_.next(e), t = !0) : this.X_(e, this.onlineState) && (this.ea(e), \n t = !0), this.Y_ = e, t;\n }\n onError(e) {\n this.H_.error(e);\n }\n /** Returns whether a snapshot was raised. */ G_(e) {\n this.onlineState = e;\n let t = !1;\n return this.Y_ && !this.J_ && this.X_(this.Y_, e) && (this.ea(this.Y_), t = !0), \n t;\n }\n X_(e, t) {\n // Always raise the first event when we're synced\n if (!e.fromCache) return !0;\n // Always raise event if listening to cache\n if (!this.U_()) return !0;\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const n = \"Offline\" /* OnlineState.Offline */ !== t;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n return (!this.options.ta || !n) && (!e.docs.isEmpty() || e.hasCachedResults || \"Offline\" /* OnlineState.Offline */ === t);\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n }\n Z_(e) {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (e.docChanges.length > 0) return !0;\n const t = this.Y_ && this.Y_.hasPendingWrites !== e.hasPendingWrites;\n return !(!e.syncStateChanged && !t) && !0 === this.options.includeMetadataChanges;\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n }\n ea(e) {\n e = ViewSnapshot.fromInitialDocuments(e.query, e.docs, e.mutatedKeys, e.fromCache, e.hasCachedResults), \n this.J_ = !0, this.H_.next(e);\n }\n U_() {\n return this.options.source !== me.Cache;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */ class __PRIVATE_SizedBundleElement {\n constructor(e, \n // How many bytes this element takes to store in the bundle.\n t) {\n this.na = e, this.byteLength = t;\n }\n ra() {\n return \"metadata\" in this.na;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */ class __PRIVATE_BundleConverterImpl {\n constructor(e) {\n this.serializer = e;\n }\n Ps(e) {\n return fromName(this.serializer, e);\n }\n /**\n * Converts a BundleDocument to a MutableDocument.\n */ Is(e) {\n return e.metadata.exists ? __PRIVATE_fromDocument(this.serializer, e.document, !1) : MutableDocument.newNoDocument(this.Ps(e.metadata.name), this.Ts(e.metadata.readTime));\n }\n Ts(e) {\n return __PRIVATE_fromVersion(e);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */ class __PRIVATE_BundleLoader {\n constructor(e, t, n) {\n this.ia = e, this.localStore = t, this.serializer = n, \n /** Batched queries to be saved into storage */\n this.queries = [], \n /** Batched documents to be saved into storage */\n this.documents = [], \n /** The collection groups affected by this bundle. */\n this.collectionGroups = new Set, this.progress = __PRIVATE_bundleInitialProgress(e);\n }\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */ sa(e) {\n this.progress.bytesLoaded += e.byteLength;\n let t = this.progress.documentsLoaded;\n if (e.na.namedQuery) this.queries.push(e.na.namedQuery); else if (e.na.documentMetadata) {\n this.documents.push({\n metadata: e.na.documentMetadata\n }), e.na.documentMetadata.exists || ++t;\n const n = ResourcePath.fromString(e.na.documentMetadata.name);\n this.collectionGroups.add(n.get(n.length - 2));\n } else e.na.document && (this.documents[this.documents.length - 1].document = e.na.document, \n ++t);\n return t !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t, \n Object.assign({}, this.progress)) : null;\n }\n oa(e) {\n const t = new Map, n = new __PRIVATE_BundleConverterImpl(this.serializer);\n for (const r of e) if (r.metadata.queries) {\n const e = n.Ps(r.metadata.name);\n for (const n of r.metadata.queries) {\n const r = (t.get(n) || __PRIVATE_documentKeySet()).add(e);\n t.set(n, r);\n }\n }\n return t;\n }\n /**\n * Update the progress to 'Success' and return the updated progress.\n */ async complete() {\n const e = await __PRIVATE_localStoreApplyBundledDocuments(this.localStore, new __PRIVATE_BundleConverterImpl(this.serializer), this.documents, this.ia.id), t = this.oa(this.documents);\n for (const e of this.queries) await __PRIVATE_localStoreSaveNamedQuery(this.localStore, e, t.get(e.name));\n return this.progress.taskState = \"Success\", {\n progress: this.progress,\n _a: this.collectionGroups,\n aa: e\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */ function __PRIVATE_bundleInitialProgress(e) {\n return {\n taskState: \"Running\",\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: e.totalDocuments,\n totalBytes: e.totalBytes\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass __PRIVATE_AddedLimboDocument {\n constructor(e) {\n this.key = e;\n }\n}\n\nclass __PRIVATE_RemovedLimboDocument {\n constructor(e) {\n this.key = e;\n }\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */ class __PRIVATE_View {\n constructor(e, \n /** Documents included in the remote target */\n t) {\n this.query = e, this.ua = t, this.ca = null, this.hasCachedResults = !1, \n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n this.current = !1, \n /** Documents in the view but not in the remote target */\n this.la = __PRIVATE_documentKeySet(), \n /** Document Keys that have local changes */\n this.mutatedKeys = __PRIVATE_documentKeySet(), this.ha = __PRIVATE_newQueryComparator(e), \n this.Pa = new DocumentSet(this.ha);\n }\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */ get Ia() {\n return this.ua;\n }\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */ Ta(e, t) {\n const n = t ? t.Ea : new __PRIVATE_DocumentChangeSet, r = t ? t.Pa : this.Pa;\n let i = t ? t.mutatedKeys : this.mutatedKeys, s = r, o = !1;\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const _ = \"F\" /* LimitType.First */ === this.query.limitType && r.size === this.query.limit ? r.last() : null, a = \"L\" /* LimitType.Last */ === this.query.limitType && r.size === this.query.limit ? r.first() : null;\n // Drop documents out to meet limit/limitToLast requirement.\n if (e.inorderTraversal(((e, t) => {\n const u = r.get(e), c = __PRIVATE_queryMatches(this.query, t) ? t : null, l = !!u && this.mutatedKeys.has(u.key), h = !!c && (c.hasLocalMutations || \n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n this.mutatedKeys.has(c.key) && c.hasCommittedMutations);\n let P = !1;\n // Calculate change\n if (u && c) {\n u.data.isEqual(c.data) ? l !== h && (n.track({\n type: 3 /* ChangeType.Metadata */ ,\n doc: c\n }), P = !0) : this.da(u, c) || (n.track({\n type: 2 /* ChangeType.Modified */ ,\n doc: c\n }), P = !0, (_ && this.ha(c, _) > 0 || a && this.ha(c, a) < 0) && (\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n o = !0));\n } else !u && c ? (n.track({\n type: 0 /* ChangeType.Added */ ,\n doc: c\n }), P = !0) : u && !c && (n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: u\n }), P = !0, (_ || a) && (\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n o = !0));\n P && (c ? (s = s.add(c), i = h ? i.add(e) : i.delete(e)) : (s = s.delete(e), i = i.delete(e)));\n })), null !== this.query.limit) for (;s.size > this.query.limit; ) {\n const e = \"F\" /* LimitType.First */ === this.query.limitType ? s.last() : s.first();\n s = s.delete(e.key), i = i.delete(e.key), n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: e\n });\n }\n return {\n Pa: s,\n Ea: n,\n Xi: o,\n mutatedKeys: i\n };\n }\n da(e, t) {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return e.hasLocalMutations && t.hasCommittedMutations && !t.hasLocalMutations;\n }\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(e, t, n, r) {\n const i = this.Pa;\n this.Pa = e.Pa, this.mutatedKeys = e.mutatedKeys;\n // Sort changes based on type and query comparator\n const s = e.Ea.k_();\n s.sort(((e, t) => function __PRIVATE_compareChangeType(e, t) {\n const order = e => {\n switch (e) {\n case 0 /* ChangeType.Added */ :\n return 1;\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n\n case 1 /* ChangeType.Removed */ :\n return 0;\n\n default:\n return fail();\n }\n };\n return order(e) - order(t);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (e.type, t.type) || this.ha(e.doc, t.doc))), this.Aa(n), r = null != r && r;\n const o = t && !r ? this.Ra() : [], _ = 0 === this.la.size && this.current && !r ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , a = _ !== this.ca;\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n if (this.ca = _, 0 !== s.length || a) {\n return {\n snapshot: new ViewSnapshot(this.query, e.Pa, i, s, e.mutatedKeys, 0 /* SyncState.Local */ === _, a, \n /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),\n Va: o\n };\n }\n // no changes\n return {\n Va: o\n };\n }\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */ G_(e) {\n return this.current && \"Offline\" /* OnlineState.Offline */ === e ? (\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = !1, this.applyChanges({\n Pa: this.Pa,\n Ea: new __PRIVATE_DocumentChangeSet,\n mutatedKeys: this.mutatedKeys,\n Xi: !1\n }, \n /* limboResolutionEnabled= */ !1)) : {\n Va: []\n };\n }\n /**\n * Returns whether the doc for the given key should be in limbo.\n */ ma(e) {\n // If the remote end says it's part of this query, it's not in limbo.\n return !this.ua.has(e) && (\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n !!this.Pa.has(e) && !this.Pa.get(e).hasLocalMutations);\n }\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */ Aa(e) {\n e && (e.addedDocuments.forEach((e => this.ua = this.ua.add(e))), e.modifiedDocuments.forEach((e => {})), \n e.removedDocuments.forEach((e => this.ua = this.ua.delete(e))), this.current = e.current);\n }\n Ra() {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) return [];\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const e = this.la;\n this.la = __PRIVATE_documentKeySet(), this.Pa.forEach((e => {\n this.ma(e.key) && (this.la = this.la.add(e.key));\n }));\n // Diff the new limbo docs with the old limbo docs.\n const t = [];\n return e.forEach((e => {\n this.la.has(e) || t.push(new __PRIVATE_RemovedLimboDocument(e));\n })), this.la.forEach((n => {\n e.has(n) || t.push(new __PRIVATE_AddedLimboDocument(n));\n })), t;\n }\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n fa(e) {\n this.ua = e.hs, this.la = __PRIVATE_documentKeySet();\n const t = this.Ta(e.documents);\n return this.applyChanges(t, /* limboResolutionEnabled= */ !0);\n }\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n ga() {\n return ViewSnapshot.fromInitialDocuments(this.query, this.Pa, this.mutatedKeys, 0 /* SyncState.Local */ === this.ca, this.hasCachedResults);\n }\n}\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass __PRIVATE_QueryView {\n constructor(\n /**\n * The query itself.\n */\n e, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n t, \n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n n) {\n this.query = e, this.targetId = t, this.view = n;\n }\n}\n\n/** Tracks a limbo resolution. */ class LimboResolution {\n constructor(e) {\n this.key = e, \n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n this.pa = !1;\n }\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */ class __PRIVATE_SyncEngineImpl {\n constructor(e, t, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n r, i, s) {\n this.localStore = e, this.remoteStore = t, this.eventManager = n, this.sharedClientState = r, \n this.currentUser = i, this.maxConcurrentLimboResolutions = s, this.ya = {}, this.wa = new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals), \n this.Sa = new Map, \n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n this.ba = new Set, \n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n this.Da = new SortedMap(DocumentKey.comparator), \n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n this.Ca = new Map, this.va = new __PRIVATE_ReferenceSet, \n /** Stores user completion handlers, indexed by User and BatchId. */\n this.Fa = {}, \n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n this.Ma = new Map, this.xa = __PRIVATE_TargetIdGenerator.Ln(), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n this.Oa = void 0;\n }\n get isPrimaryClient() {\n return !0 === this.Oa;\n }\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nasync function __PRIVATE_syncEngineListen(e, t, n = !0) {\n const r = __PRIVATE_ensureWatchCallbacks(e);\n let i;\n const s = r.wa.get(t);\n return s ? (\n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n r.sharedClientState.addLocalQueryTarget(s.targetId), i = s.view.ga()) : i = await __PRIVATE_allocateTargetAndMaybeListen(r, t, n, \n /** shouldInitializeView= */ !0), i;\n}\n\n/** Query has been listening to the cache, and tries to initiate the remote store listen */ async function __PRIVATE_triggerRemoteStoreListen(e, t) {\n const n = __PRIVATE_ensureWatchCallbacks(e);\n await __PRIVATE_allocateTargetAndMaybeListen(n, t, \n /** shouldListenToRemote= */ !0, \n /** shouldInitializeView= */ !1);\n}\n\nasync function __PRIVATE_allocateTargetAndMaybeListen(e, t, n, r) {\n const i = await __PRIVATE_localStoreAllocateTarget(e.localStore, __PRIVATE_queryToTarget(t)), s = i.targetId, o = n ? e.sharedClientState.addLocalQueryTarget(s) : \"not-current\";\n let _;\n return r && (_ = await __PRIVATE_initializeViewAndComputeSnapshot(e, t, s, \"current\" === o, i.resumeToken)), \n e.isPrimaryClient && n && __PRIVATE_remoteStoreListen(e.remoteStore, i), _;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */ async function __PRIVATE_initializeViewAndComputeSnapshot(e, t, n, r, i) {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n e.Na = (t, n, r) => async function __PRIVATE_applyDocChanges(e, t, n, r) {\n let i = t.view.Ta(n);\n i.Xi && (\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n i = await __PRIVATE_localStoreExecuteQuery(e.localStore, t.query, \n /* usePreviousResults= */ !1).then((({documents: e}) => t.view.Ta(e, i))));\n const s = r && r.targetChanges.get(t.targetId), o = r && null != r.targetMismatches.get(t.targetId), _ = t.view.applyChanges(i, \n /* limboResolutionEnabled= */ e.isPrimaryClient, s, o);\n return __PRIVATE_updateTrackedLimbos(e, t.targetId, _.Va), _.snapshot;\n }(e, t, n, r);\n const s = await __PRIVATE_localStoreExecuteQuery(e.localStore, t, \n /* usePreviousResults= */ !0), o = new __PRIVATE_View(t, s.hs), _ = o.Ta(s.documents), a = TargetChange.createSynthesizedTargetChangeForCurrentChange(n, r && \"Offline\" /* OnlineState.Offline */ !== e.onlineState, i), u = o.applyChanges(_, \n /* limboResolutionEnabled= */ e.isPrimaryClient, a);\n __PRIVATE_updateTrackedLimbos(e, n, u.Va);\n const c = new __PRIVATE_QueryView(t, n, o);\n return e.wa.set(t, c), e.Sa.has(n) ? e.Sa.get(n).push(t) : e.Sa.set(n, [ t ]), u.snapshot;\n}\n\n/** Stops listening to the query. */ async function __PRIVATE_syncEngineUnlisten(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = r.wa.get(t), s = r.Sa.get(i.targetId);\n if (s.length > 1) return r.Sa.set(i.targetId, s.filter((e => !__PRIVATE_queryEquals(e, t)))), \n void r.wa.delete(t);\n // No other queries are mapped to the target, clean up the query and the target.\n if (r.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n r.sharedClientState.removeLocalQueryTarget(i.targetId);\n r.sharedClientState.isActiveQueryTarget(i.targetId) || await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, \n /*keepPersistedTargetData=*/ !1).then((() => {\n r.sharedClientState.clearQueryState(i.targetId), n && __PRIVATE_remoteStoreUnlisten(r.remoteStore, i.targetId), \n __PRIVATE_removeAndCleanupTarget(r, i.targetId);\n })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n } else __PRIVATE_removeAndCleanupTarget(r, i.targetId), await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, \n /*keepPersistedTargetData=*/ !0);\n}\n\n/** Unlistens to the remote store while still listening to the cache. */ async function __PRIVATE_triggerRemoteStoreUnlisten(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.wa.get(t), i = n.Sa.get(r.targetId);\n n.isPrimaryClient && 1 === i.length && (\n // PORTING NOTE: Unregister the target ID with local Firestore client as\n // watch target.\n n.sharedClientState.removeLocalQueryTarget(r.targetId), __PRIVATE_remoteStoreUnlisten(n.remoteStore, r.targetId));\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */ async function __PRIVATE_syncEngineWrite(e, t, n) {\n const r = __PRIVATE_syncEngineEnsureWriteCallbacks(e);\n try {\n const e = await function __PRIVATE_localStoreWriteLocally(e, t) {\n const n = __PRIVATE_debugCast(e), r = Timestamp.now(), i = t.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet());\n let s, o;\n return n.persistence.runTransaction(\"Locally write mutations\", \"readwrite\", (e => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();\n return n.os.getEntries(e, i).next((e => {\n _ = e, _.forEach(((e, t) => {\n t.isValidDocument() || (a = a.add(e));\n }));\n })).next((() => n.localDocuments.getOverlayedDocuments(e, _))).next((i => {\n s = i;\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const o = [];\n for (const e of t) {\n const t = __PRIVATE_mutationExtractBaseValue(e, s.get(e.key).overlayedDocument);\n null != t && \n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n o.push(new __PRIVATE_PatchMutation(e.key, t, __PRIVATE_extractFieldMask(t.value.mapValue), Precondition.exists(!0)));\n }\n return n.mutationQueue.addMutationBatch(e, r, o, t);\n })).next((t => {\n o = t;\n const r = t.applyToLocalDocumentSet(s, a);\n return n.documentOverlayCache.saveOverlays(e, t.batchId, r);\n }));\n })).then((() => ({\n batchId: o.batchId,\n changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s)\n })));\n }(r.localStore, t);\n r.sharedClientState.addPendingMutation(e.batchId), function __PRIVATE_addMutationCallback(e, t, n) {\n let r = e.Fa[e.currentUser.toKey()];\n r || (r = new SortedMap(__PRIVATE_primitiveComparator));\n r = r.insert(t, n), e.Fa[e.currentUser.toKey()] = r;\n }\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */ (r, e.batchId, n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e.changes), \n await __PRIVATE_fillWritePipeline(r.remoteStore);\n } catch (e) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const t = __PRIVATE_wrapInUserErrorIfRecoverable(e, \"Failed to persist write\");\n n.reject(t);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */ async function __PRIVATE_syncEngineApplyRemoteEvent(e, t) {\n const n = __PRIVATE_debugCast(e);\n try {\n const e = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n.localStore, t);\n // Update `receivedDocument` as appropriate for any limbo targets.\n t.targetChanges.forEach(((e, t) => {\n const r = n.Ca.get(t);\n r && (\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n __PRIVATE_hardAssert(e.addedDocuments.size + e.modifiedDocuments.size + e.removedDocuments.size <= 1), \n e.addedDocuments.size > 0 ? r.pa = !0 : e.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r.pa) : e.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r.pa), \n r.pa = !1));\n })), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e, t);\n } catch (e) {\n await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */ function __PRIVATE_syncEngineApplyOnlineStateChange(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {\n const e = [];\n r.wa.forEach(((n, r) => {\n const i = r.view.G_(t);\n i.snapshot && e.push(i.snapshot);\n })), function __PRIVATE_eventManagerOnOnlineStateChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n n.onlineState = t;\n let r = !1;\n n.queries.forEach(((e, n) => {\n for (const e of n.Q_) \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n e.G_(t) && (r = !0);\n })), r && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n }(r.eventManager, t), e.length && r.ya.u_(e), r.onlineState = t, r.isPrimaryClient && r.sharedClientState.setOnlineState(t);\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */ async function __PRIVATE_syncEngineRejectListen(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n // PORTING NOTE: Multi-tab only.\n r.sharedClientState.updateQueryState(t, \"rejected\", n);\n const i = r.Ca.get(t), s = i && i.key;\n if (s) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let e = new SortedMap(DocumentKey.comparator);\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n e = e.insert(s, MutableDocument.newNoDocument(s, SnapshotVersion.min()));\n const n = __PRIVATE_documentKeySet().add(s), i = new RemoteEvent(SnapshotVersion.min(), \n /* targetChanges= */ new Map, \n /* targetMismatches= */ new SortedMap(__PRIVATE_primitiveComparator), e, n);\n await __PRIVATE_syncEngineApplyRemoteEvent(r, i), \n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n r.Da = r.Da.remove(s), r.Ca.delete(t), __PRIVATE_pumpEnqueuedLimboResolutions(r);\n } else await __PRIVATE_localStoreReleaseTarget(r.localStore, t, \n /* keepPersistedTargetData */ !1).then((() => __PRIVATE_removeAndCleanupTarget(r, t, n))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n}\n\nasync function __PRIVATE_syncEngineApplySuccessfulWrite(e, t) {\n const n = __PRIVATE_debugCast(e), r = t.batch.batchId;\n try {\n const e = await __PRIVATE_localStoreAcknowledgeBatch(n.localStore, t);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n __PRIVATE_processUserCallback(n, r, /*error=*/ null), __PRIVATE_triggerPendingWritesCallbacks(n, r), \n n.sharedClientState.updateMutationState(r, \"acknowledged\"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e);\n } catch (e) {\n await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n }\n}\n\nasync function __PRIVATE_syncEngineRejectFailedWrite(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n try {\n const e = await function __PRIVATE_localStoreRejectBatch(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Reject batch\", \"readwrite-primary\", (e => {\n let r;\n return n.mutationQueue.lookupMutationBatch(e, t).next((t => (__PRIVATE_hardAssert(null !== t), \n r = t.keys(), n.mutationQueue.removeMutationBatch(e, t)))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, r))).next((() => n.localDocuments.getDocuments(e, r)));\n }));\n }\n /**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */ (r.localStore, t);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n __PRIVATE_processUserCallback(r, t, n), __PRIVATE_triggerPendingWritesCallbacks(r, t), \n r.sharedClientState.updateMutationState(t, \"rejected\", n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e);\n } catch (n) {\n await __PRIVATE_ignoreIfPrimaryLeaseLoss(n);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */ async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e, t) {\n const n = __PRIVATE_debugCast(e);\n __PRIVATE_canUseNetwork(n.remoteStore) || __PRIVATE_logDebug(\"SyncEngine\", \"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\");\n try {\n const e = await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e) {\n const t = __PRIVATE_debugCast(e);\n return t.persistence.runTransaction(\"Get highest unacknowledged batch id\", \"readonly\", (e => t.mutationQueue.getHighestUnacknowledgedBatchId(e)));\n }(n.localStore);\n if (-1 === e) \n // Trigger the callback right away if there is no pending writes at the moment.\n return void t.resolve();\n const r = n.Ma.get(e) || [];\n r.push(t), n.Ma.set(e, r);\n } catch (e) {\n const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, \"Initialization of waitForPendingWrites() operation failed\");\n t.reject(n);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */ function __PRIVATE_triggerPendingWritesCallbacks(e, t) {\n (e.Ma.get(t) || []).forEach((e => {\n e.resolve();\n })), e.Ma.delete(t);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */ function __PRIVATE_processUserCallback(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n let i = r.Fa[r.currentUser.toKey()];\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (i) {\n const e = i.get(t);\n e && (n ? e.reject(n) : e.resolve(), i = i.remove(t)), r.Fa[r.currentUser.toKey()] = i;\n }\n}\n\nfunction __PRIVATE_removeAndCleanupTarget(e, t, n = null) {\n e.sharedClientState.removeLocalQueryTarget(t);\n for (const r of e.Sa.get(t)) e.wa.delete(r), n && e.ya.La(r, n);\n if (e.Sa.delete(t), e.isPrimaryClient) {\n e.va.Vr(t).forEach((t => {\n e.va.containsKey(t) || \n // We removed the last reference for this key\n __PRIVATE_removeLimboTarget(e, t);\n }));\n }\n}\n\nfunction __PRIVATE_removeLimboTarget(e, t) {\n e.ba.delete(t.path.canonicalString());\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const n = e.Da.get(t);\n null !== n && (__PRIVATE_remoteStoreUnlisten(e.remoteStore, n), e.Da = e.Da.remove(t), \n e.Ca.delete(n), __PRIVATE_pumpEnqueuedLimboResolutions(e));\n}\n\nfunction __PRIVATE_updateTrackedLimbos(e, t, n) {\n for (const r of n) if (r instanceof __PRIVATE_AddedLimboDocument) e.va.addReference(r.key, t), \n __PRIVATE_trackLimboChange(e, r); else if (r instanceof __PRIVATE_RemovedLimboDocument) {\n __PRIVATE_logDebug(\"SyncEngine\", \"Document no longer in limbo: \" + r.key), e.va.removeReference(r.key, t);\n e.va.containsKey(r.key) || \n // We removed the last reference for this key\n __PRIVATE_removeLimboTarget(e, r.key);\n } else fail();\n}\n\nfunction __PRIVATE_trackLimboChange(e, t) {\n const n = t.key, r = n.path.canonicalString();\n e.Da.get(n) || e.ba.has(r) || (__PRIVATE_logDebug(\"SyncEngine\", \"New document in limbo: \" + n), \n e.ba.add(r), __PRIVATE_pumpEnqueuedLimboResolutions(e));\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */ function __PRIVATE_pumpEnqueuedLimboResolutions(e) {\n for (;e.ba.size > 0 && e.Da.size < e.maxConcurrentLimboResolutions; ) {\n const t = e.ba.values().next().value;\n e.ba.delete(t);\n const n = new DocumentKey(ResourcePath.fromString(t)), r = e.xa.next();\n e.Ca.set(r, new LimboResolution(n)), e.Da = e.Da.insert(n, r), __PRIVATE_remoteStoreListen(e.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n.path)), r, \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ , __PRIVATE_ListenSequence._e));\n }\n}\n\nasync function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = [], s = [], o = [];\n r.wa.isEmpty() || (r.wa.forEach(((e, _) => {\n o.push(r.Na(_, t, n).then((e => {\n // Update views if there are actual changes.\n if (\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n (e || n) && r.isPrimaryClient && r.sharedClientState.updateQueryState(_.targetId, (null == e ? void 0 : e.fromCache) ? \"not-current\" : \"current\"), \n e) {\n i.push(e);\n const t = __PRIVATE_LocalViewChanges.Ki(_.targetId, e);\n s.push(t);\n }\n })));\n })), await Promise.all(o), r.ya.u_(i), await async function __PRIVATE_localStoreNotifyLocalViewChanges(e, t) {\n const n = __PRIVATE_debugCast(e);\n try {\n await n.persistence.runTransaction(\"notifyLocalViewChanges\", \"readwrite\", (e => PersistencePromise.forEach(t, (t => PersistencePromise.forEach(t.qi, (r => n.persistence.referenceDelegate.addReference(e, t.targetId, r))).next((() => PersistencePromise.forEach(t.Qi, (r => n.persistence.referenceDelegate.removeReference(e, t.targetId, r)))))))));\n } catch (e) {\n if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n __PRIVATE_logDebug(\"LocalStore\", \"Failed to update sequence numbers: \" + e);\n }\n for (const e of t) {\n const t = e.targetId;\n if (!e.fromCache) {\n const e = n.ns.get(t), r = e.snapshotVersion, i = e.withLastLimboFreeSnapshotVersion(r);\n // Advance the last limbo free snapshot version\n n.ns = n.ns.insert(t, i);\n }\n }\n }(r.localStore, s));\n}\n\nasync function __PRIVATE_syncEngineHandleCredentialChange(e, t) {\n const n = __PRIVATE_debugCast(e);\n if (!n.currentUser.isEqual(t)) {\n __PRIVATE_logDebug(\"SyncEngine\", \"User change. New user:\", t.toKey());\n const e = await __PRIVATE_localStoreHandleUserChange(n.localStore, t);\n n.currentUser = t, \n // Fails tasks waiting for pending writes requested by previous user.\n function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e, t) {\n e.Ma.forEach((e => {\n e.forEach((e => {\n e.reject(new FirestoreError(D.CANCELLED, t));\n }));\n })), e.Ma.clear();\n }(n, \"'waitForPendingWrites' promise is rejected due to a user change.\"), \n // TODO(b/114226417): Consider calling this only in the primary tab.\n n.sharedClientState.handleUserChange(t, e.removedBatchIds, e.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e.us);\n }\n}\n\nfunction __PRIVATE_syncEngineGetRemoteKeysForTarget(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.Ca.get(t);\n if (r && r.pa) return __PRIVATE_documentKeySet().add(r.key);\n {\n let e = __PRIVATE_documentKeySet();\n const r = n.Sa.get(t);\n if (!r) return e;\n for (const t of r) {\n const r = n.wa.get(t);\n e = e.unionWith(r.view.Ia);\n }\n return e;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */ async function __PRIVATE_synchronizeViewAndComputeSnapshot(e, t) {\n const n = __PRIVATE_debugCast(e), r = await __PRIVATE_localStoreExecuteQuery(n.localStore, t.query, \n /* usePreviousResults= */ !0), i = t.view.fa(r);\n return n.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n, t.targetId, i.Va), \n i;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e, t) {\n const n = __PRIVATE_debugCast(e);\n return __PRIVATE_localStoreGetNewDocumentChanges(n.localStore, t).then((e => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e)));\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyBatchState(e, t, n, r) {\n const i = __PRIVATE_debugCast(e), s = await function __PRIVATE_localStoreLookupMutationDocuments(e, t) {\n const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.mutationQueue);\n return n.persistence.runTransaction(\"Lookup mutation documents\", \"readonly\", (e => r.vn(e, t).next((t => t ? n.localDocuments.getDocuments(e, t) : PersistencePromise.resolve(null)))));\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, t);\n null !== s ? (\"pending\" === n ? \n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await __PRIVATE_fillWritePipeline(i.remoteStore) : \"acknowledged\" === n || \"rejected\" === n ? (\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n __PRIVATE_processUserCallback(i, t, r || null), __PRIVATE_triggerPendingWritesCallbacks(i, t), \n function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e, t) {\n __PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).Mn(t);\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, t)) : fail(), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, s)) : \n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n __PRIVATE_logDebug(\"SyncEngine\", \"Cannot apply mutation batch with id: \" + t);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyPrimaryState(e, t) {\n const n = __PRIVATE_debugCast(e);\n if (__PRIVATE_ensureWatchCallbacks(n), __PRIVATE_syncEngineEnsureWriteCallbacks(n), \n !0 === t && !0 !== n.Oa) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const e = n.sharedClientState.getAllActiveQueryTargets(), t = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e.toArray());\n n.Oa = !0, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !0);\n for (const e of t) __PRIVATE_remoteStoreListen(n.remoteStore, e);\n } else if (!1 === t && !1 !== n.Oa) {\n const e = [];\n let t = Promise.resolve();\n n.Sa.forEach(((r, i) => {\n n.sharedClientState.isLocalQueryTarget(i) ? e.push(i) : t = t.then((() => (__PRIVATE_removeAndCleanupTarget(n, i), \n __PRIVATE_localStoreReleaseTarget(n.localStore, i, \n /*keepPersistedTargetData=*/ !0)))), __PRIVATE_remoteStoreUnlisten(n.remoteStore, i);\n })), await t, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e), \n // PORTING NOTE: Multi-Tab only.\n function __PRIVATE_resetLimboDocuments(e) {\n const t = __PRIVATE_debugCast(e);\n t.Ca.forEach(((e, n) => {\n __PRIVATE_remoteStoreUnlisten(t.remoteStore, n);\n })), t.va.mr(), t.Ca = new Map, t.Da = new SortedMap(DocumentKey.comparator);\n }\n /**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n // PORTING NOTE: Multi-Tab only.\n (n), n.Oa = !1, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !1);\n }\n}\n\nasync function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e, t, n) {\n const r = __PRIVATE_debugCast(e), i = [], s = [];\n for (const e of t) {\n let t;\n const n = r.Sa.get(e);\n if (n && 0 !== n.length) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n t = await __PRIVATE_localStoreAllocateTarget(r.localStore, __PRIVATE_queryToTarget(n[0]));\n for (const e of n) {\n const t = r.wa.get(e), n = await __PRIVATE_synchronizeViewAndComputeSnapshot(r, t);\n n.snapshot && s.push(n.snapshot);\n }\n } else {\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const n = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e);\n t = await __PRIVATE_localStoreAllocateTarget(r.localStore, n), await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(n), e, \n /*current=*/ !1, t.resumeToken);\n }\n i.push(t);\n }\n return r.ya.u_(s), i;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_synthesizeTargetToQuery(e) {\n return __PRIVATE_newQuery(e.path, e.collectionGroup, e.orderBy, e.filters, e.limit, \"F\" /* LimitType.First */ , e.startAt, e.endAt);\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_syncEngineGetActiveClients(e) {\n return function __PRIVATE_localStoreGetActiveClients(e) {\n return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).Bi();\n }(__PRIVATE_debugCast(e).localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyTargetState(e, t, n, r) {\n const i = __PRIVATE_debugCast(e);\n if (i.Oa) \n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n return void __PRIVATE_logDebug(\"SyncEngine\", \"Ignoring unexpected query state notification.\");\n const s = i.Sa.get(t);\n if (s && s.length > 0) switch (n) {\n case \"current\":\n case \"not-current\":\n {\n const e = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, __PRIVATE_queryCollectionGroup(s[0])), r = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t, \"current\" === n, ByteString.EMPTY_BYTE_STRING);\n await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, e, r);\n break;\n }\n\n case \"rejected\":\n await __PRIVATE_localStoreReleaseTarget(i.localStore, t, \n /* keepPersistedTargetData */ !0), __PRIVATE_removeAndCleanupTarget(i, t, r);\n break;\n\n default:\n fail();\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */ async function __PRIVATE_syncEngineApplyActiveTargetsChange(e, t, n) {\n const r = __PRIVATE_ensureWatchCallbacks(e);\n if (r.Oa) {\n for (const e of t) {\n if (r.Sa.has(e) && r.sharedClientState.isActiveQueryTarget(e)) {\n __PRIVATE_logDebug(\"SyncEngine\", \"Adding an already active target \" + e);\n continue;\n }\n const t = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e), n = await __PRIVATE_localStoreAllocateTarget(r.localStore, t);\n await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(t), n.targetId, \n /*current=*/ !1, n.resumeToken), __PRIVATE_remoteStoreListen(r.remoteStore, n);\n }\n for (const e of n) \n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n r.Sa.has(e) && \n // Release queries that are still active.\n await __PRIVATE_localStoreReleaseTarget(r.localStore, e, \n /* keepPersistedTargetData */ !1).then((() => {\n __PRIVATE_remoteStoreUnlisten(r.remoteStore, e), __PRIVATE_removeAndCleanupTarget(r, e);\n })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n }\n}\n\nfunction __PRIVATE_ensureWatchCallbacks(e) {\n const t = __PRIVATE_debugCast(e);\n return t.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t), \n t.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t), \n t.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t), \n t.ya.u_ = __PRIVATE_eventManagerOnWatchChange.bind(null, t.eventManager), t.ya.La = __PRIVATE_eventManagerOnWatchError.bind(null, t.eventManager), \n t;\n}\n\nfunction __PRIVATE_syncEngineEnsureWriteCallbacks(e) {\n const t = __PRIVATE_debugCast(e);\n return t.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t), \n t.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t), \n t;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */ function __PRIVATE_syncEngineLoadBundle(e, t, n) {\n const r = __PRIVATE_debugCast(e);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (\n /** Loads a bundle and returns the list of affected collection groups. */\n async function __PRIVATE_loadBundleImpl(e, t, n) {\n try {\n const r = await t.getMetadata();\n if (await function __PRIVATE_localStoreHasNewerBundle(e, t) {\n const n = __PRIVATE_debugCast(e), r = __PRIVATE_fromVersion(t.createTime);\n return n.persistence.runTransaction(\"hasNewerBundle\", \"readonly\", (e => n.$r.getBundleMetadata(e, t.id))).then((e => !!e && e.createTime.compareTo(r) >= 0));\n }\n /**\n * Saves the given `BundleMetadata` to local persistence.\n */ (e.localStore, r)) return await t.close(), n._completeWith(function __PRIVATE_bundleSuccessProgress(e) {\n return {\n taskState: \"Success\",\n documentsLoaded: e.totalDocuments,\n bytesLoaded: e.totalBytes,\n totalDocuments: e.totalDocuments,\n totalBytes: e.totalBytes\n };\n }(r)), Promise.resolve(new Set);\n n._updateProgress(__PRIVATE_bundleInitialProgress(r));\n const i = new __PRIVATE_BundleLoader(r, e.localStore, t.serializer);\n let s = await t.Ba();\n for (;s; ) {\n const e = await i.sa(s);\n e && n._updateProgress(e), s = await t.Ba();\n }\n const o = await i.complete();\n return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, o.aa, \n /* remoteEvent */ void 0), \n // Save metadata, so loading the same bundle will skip.\n await function __PRIVATE_localStoreSaveBundle(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Save bundle\", \"readwrite\", (e => n.$r.saveBundleMetadata(e, t)));\n }\n /**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */ (e.localStore, r), n._completeWith(o.progress), Promise.resolve(o._a);\n } catch (e) {\n return __PRIVATE_logWarn(\"SyncEngine\", `Loading bundle failed with ${e}`), n._failWith(e), \n Promise.resolve(new Set);\n }\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */)(r, t, n).then((e => {\n r.sharedClientState.notifyBundleLoaded(e);\n }));\n}\n\nclass MemoryOfflineComponentProvider {\n constructor() {\n this.synchronizeTabs = !1;\n }\n async initialize(e) {\n this.serializer = __PRIVATE_newSerializer(e.databaseInfo.databaseId), this.sharedClientState = this.createSharedClientState(e), \n this.persistence = this.createPersistence(e), await this.persistence.start(), this.localStore = this.createLocalStore(e), \n this.gcScheduler = this.createGarbageCollectionScheduler(e, this.localStore), this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(e, this.localStore);\n }\n createGarbageCollectionScheduler(e, t) {\n return null;\n }\n createIndexBackfillerScheduler(e, t) {\n return null;\n }\n createLocalStore(e) {\n return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer);\n }\n createPersistence(e) {\n return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Hr, this.serializer);\n }\n createSharedClientState(e) {\n return new __PRIVATE_MemorySharedClientState;\n }\n async terminate() {\n var e, t;\n null === (e = this.gcScheduler) || void 0 === e || e.stop(), null === (t = this.indexBackfillerScheduler) || void 0 === t || t.stop(), \n this.sharedClientState.shutdown(), await this.persistence.shutdown();\n }\n}\n\nclass __PRIVATE_LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider {\n constructor(e) {\n super(), this.cacheSizeBytes = e;\n }\n createGarbageCollectionScheduler(e, t) {\n __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate);\n const n = this.persistence.referenceDelegate.garbageCollector;\n return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);\n }\n createPersistence(e) {\n const t = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;\n return new __PRIVATE_MemoryPersistence((e => __PRIVATE_MemoryLruDelegate.Hr(e, t)), this.serializer);\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */ class __PRIVATE_IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider {\n constructor(e, t, n) {\n super(), this.ka = e, this.cacheSizeBytes = t, this.forceOwnership = n, this.synchronizeTabs = !1;\n }\n async initialize(e) {\n await super.initialize(e), await this.ka.initialize(this, e), \n // Enqueue writes from a previous session\n await __PRIVATE_syncEngineEnsureWriteCallbacks(this.ka.syncEngine), await __PRIVATE_fillWritePipeline(this.ka.remoteStore), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.fi((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), \n this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), \n Promise.resolve())));\n }\n createLocalStore(e) {\n return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer);\n }\n createGarbageCollectionScheduler(e, t) {\n const n = this.persistence.referenceDelegate.garbageCollector;\n return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);\n }\n createIndexBackfillerScheduler(e, t) {\n const n = new __PRIVATE_IndexBackfiller(t, this.persistence);\n return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue, n);\n }\n createPersistence(e) {\n const t = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;\n return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t, e.clientId, n, e.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership);\n }\n createSharedClientState(e) {\n return new __PRIVATE_MemorySharedClientState;\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */ class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider {\n constructor(e, t) {\n super(e, t, /* forceOwnership= */ !1), this.ka = e, this.cacheSizeBytes = t, this.synchronizeTabs = !0;\n }\n async initialize(e) {\n await super.initialize(e);\n const t = this.ka.syncEngine;\n this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = {\n Zs: __PRIVATE_syncEngineApplyBatchState.bind(null, t),\n Xs: __PRIVATE_syncEngineApplyTargetState.bind(null, t),\n eo: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t),\n Bi: __PRIVATE_syncEngineGetActiveClients.bind(null, t),\n Ys: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t)\n }, await this.sharedClientState.start()), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.fi((async e => {\n await __PRIVATE_syncEngineApplyPrimaryState(this.ka.syncEngine, e), this.gcScheduler && (e && !this.gcScheduler.started ? this.gcScheduler.start() : e || this.gcScheduler.stop()), \n this.indexBackfillerScheduler && (e && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e || this.indexBackfillerScheduler.stop());\n }));\n }\n createSharedClientState(e) {\n const t = __PRIVATE_getWindow();\n if (!__PRIVATE_WebStorageSharedClientState.D(t)) throw new FirestoreError(D.UNIMPLEMENTED, \"IndexedDB persistence is only available on platforms that support LocalStorage.\");\n const n = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey);\n return new __PRIVATE_WebStorageSharedClientState(t, e.asyncQueue, n, e.clientId, e.initialUser);\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */ class OnlineComponentProvider {\n async initialize(e, t) {\n this.localStore || (this.localStore = e.localStore, this.sharedClientState = e.sharedClientState, \n this.datastore = this.createDatastore(t), this.remoteStore = this.createRemoteStore(t), \n this.eventManager = this.createEventManager(t), this.syncEngine = this.createSyncEngine(t, \n /* startAsPrimary=*/ !e.synchronizeTabs), this.sharedClientState.onlineStateHandler = e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 1 /* OnlineStateSource.SharedClientState */), \n this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), \n await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient));\n }\n createEventManager(e) {\n return function __PRIVATE_newEventManager() {\n return new __PRIVATE_EventManagerImpl;\n }();\n }\n createDatastore(e) {\n const t = __PRIVATE_newSerializer(e.databaseInfo.databaseId), n = function __PRIVATE_newConnection(e) {\n return new __PRIVATE_WebChannelConnection(e);\n }\n /** Return the Platform-specific connectivity monitor. */ (e.databaseInfo);\n return function __PRIVATE_newDatastore(e, t, n, r) {\n return new __PRIVATE_DatastoreImpl(e, t, n, r);\n }(e.authCredentials, e.appCheckCredentials, n, t);\n }\n createRemoteStore(e) {\n return function __PRIVATE_newRemoteStore(e, t, n, r, i) {\n return new __PRIVATE_RemoteStoreImpl(e, t, n, r, i);\n }\n /** Re-enables the network. Idempotent. */ (this.localStore, this.datastore, e.asyncQueue, (e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 0 /* OnlineStateSource.RemoteStore */)), function __PRIVATE_newConnectivityMonitor() {\n return __PRIVATE_BrowserConnectivityMonitor.D() ? new __PRIVATE_BrowserConnectivityMonitor : new __PRIVATE_NoopConnectivityMonitor;\n }());\n }\n createSyncEngine(e, t) {\n return function __PRIVATE_newSyncEngine(e, t, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n r, i, s, o) {\n const _ = new __PRIVATE_SyncEngineImpl(e, t, n, r, i, s);\n return o && (_.Oa = !0), _;\n }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e.initialUser, e.maxConcurrentLimboResolutions, t);\n }\n async terminate() {\n var e;\n await async function __PRIVATE_remoteStoreShutdown(e) {\n const t = __PRIVATE_debugCast(e);\n __PRIVATE_logDebug(\"RemoteStore\", \"RemoteStore shutting down.\"), t.v_.add(5 /* OfflineCause.Shutdown */), \n await __PRIVATE_disableNetworkInternal(t), t.M_.shutdown(), \n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n t.x_.set(\"Unknown\" /* OnlineState.Unknown */);\n }(this.remoteStore), null === (e = this.datastore) || void 0 === e || e.terminate();\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 * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nfunction __PRIVATE_toByteStreamReaderHelper(e, t = 10240) {\n let n = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read() {\n if (n < e.byteLength) {\n const r = {\n value: e.slice(n, n + t),\n done: !1\n };\n return n += t, r;\n }\n return {\n done: !0\n };\n },\n async cancel() {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nclass __PRIVATE_AsyncObserver {\n constructor(e) {\n this.observer = e, \n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = !1;\n }\n next(e) {\n this.observer.next && this.qa(this.observer.next, e);\n }\n error(e) {\n this.observer.error ? this.qa(this.observer.error, e) : __PRIVATE_logError(\"Uncaught Error in snapshot listener:\", e.toString());\n }\n Qa() {\n this.muted = !0;\n }\n qa(e, t) {\n this.muted || setTimeout((() => {\n this.muted || e(t);\n }), 0);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */ class __PRIVATE_BundleReaderImpl {\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n e, t) {\n this.Ka = e, this.serializer = t, \n /** Cached bundle metadata. */\n this.metadata = new __PRIVATE_Deferred, \n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n this.buffer = new Uint8Array, this.$a = function __PRIVATE_newTextDecoder() {\n return new TextDecoder(\"utf-8\");\n }(), \n // Read the metadata (which is the first element).\n this.Ua().then((e => {\n e && e.ra() ? this.metadata.resolve(e.na.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\\n ${JSON.stringify(null == e ? void 0 : e.na)}`));\n }), (e => this.metadata.reject(e)));\n }\n close() {\n return this.Ka.cancel();\n }\n async getMetadata() {\n return this.metadata.promise;\n }\n async Ba() {\n // Makes sure metadata is read before proceeding.\n return await this.getMetadata(), this.Ua();\n }\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */ async Ua() {\n const e = await this.Wa();\n if (null === e) return null;\n const t = this.$a.decode(e), n = Number(t);\n isNaN(n) && this.Ga(`length string (${t}) is not valid number`);\n const r = await this.za(n);\n return new __PRIVATE_SizedBundleElement(JSON.parse(r), e.length + n);\n }\n /** First index of '{' from the underlying buffer. */ ja() {\n return this.buffer.findIndex((e => e === \"{\".charCodeAt(0)));\n }\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */ async Wa() {\n for (;this.ja() < 0; ) {\n if (await this.Ha()) break;\n }\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (0 === this.buffer.length) return null;\n const e = this.ja();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n e < 0 && this.Ga(\"Reached the end of bundle when a length string is expected.\");\n const t = this.buffer.slice(0, e);\n // Update the internal buffer to drop the read length.\n return this.buffer = this.buffer.slice(e), t;\n }\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */ async za(e) {\n for (;this.buffer.length < e; ) {\n await this.Ha() && this.Ga(\"Reached the end of bundle when more is expected.\");\n }\n const t = this.$a.decode(this.buffer.slice(0, e));\n // Update the internal buffer to drop the read json string.\n return this.buffer = this.buffer.slice(e), t;\n }\n Ga(e) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n throw this.Ka.cancel(), new Error(`Invalid bundle format: ${e}`);\n }\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */ async Ha() {\n const e = await this.Ka.read();\n if (!e.done) {\n const t = new Uint8Array(this.buffer.length + e.value.length);\n t.set(this.buffer), t.set(e.value, this.buffer.length), this.buffer = t;\n }\n return e.done;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nclass Transaction$2 {\n constructor(e) {\n this.datastore = e, \n // The version of each document that was read during this transaction.\n this.readVersions = new Map, this.mutations = [], this.committed = !1, \n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n this.lastTransactionError = null, \n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n this.writtenDocs = new Set;\n }\n async lookup(e) {\n if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(D.INVALID_ARGUMENT, \"Firestore transactions require all reads to be executed before all writes.\"), \n this.lastTransactionError;\n const t = await async function __PRIVATE_invokeBatchGetDocumentsRpc(e, t) {\n const n = __PRIVATE_debugCast(e), r = {\n documents: t.map((e => __PRIVATE_toName(n.serializer, e)))\n }, i = await n.vo(\"BatchGetDocuments\", n.serializer.databaseId, ResourcePath.emptyPath(), r, t.length), s = new Map;\n i.forEach((e => {\n const t = __PRIVATE_fromBatchGetDocumentsResponse(n.serializer, e);\n s.set(t.key.toString(), t);\n }));\n const o = [];\n return t.forEach((e => {\n const t = s.get(e.toString());\n __PRIVATE_hardAssert(!!t), o.push(t);\n })), o;\n }(this.datastore, e);\n return t.forEach((e => this.recordVersion(e))), t;\n }\n set(e, t) {\n this.write(t.toMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());\n }\n update(e, t) {\n try {\n this.write(t.toMutation(e, this.preconditionForUpdate(e)));\n } catch (e) {\n this.lastTransactionError = e;\n }\n this.writtenDocs.add(e.toString());\n }\n delete(e) {\n this.write(new __PRIVATE_DeleteMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());\n }\n async commit() {\n if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError;\n const e = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach((t => {\n e.delete(t.key.toString());\n })), \n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n e.forEach(((e, t) => {\n const n = DocumentKey.fromPath(t);\n this.mutations.push(new __PRIVATE_VerifyMutation(n, this.precondition(n)));\n })), await async function __PRIVATE_invokeCommitRpc(e, t) {\n const n = __PRIVATE_debugCast(e), r = {\n writes: t.map((e => toMutation(n.serializer, e)))\n };\n await n.So(\"Commit\", n.serializer.databaseId, ResourcePath.emptyPath(), r);\n }(this.datastore, this.mutations), this.committed = !0;\n }\n recordVersion(e) {\n let t;\n if (e.isFoundDocument()) t = e.version; else {\n if (!e.isNoDocument()) throw fail();\n // Represent a deleted doc using SnapshotVersion.min().\n t = SnapshotVersion.min();\n }\n const n = this.readVersions.get(e.key.toString());\n if (n) {\n if (!t.isEqual(n)) \n // This transaction will fail no matter what.\n throw new FirestoreError(D.ABORTED, \"Document version changed between two reads.\");\n } else this.readVersions.set(e.key.toString(), t);\n }\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */ precondition(e) {\n const t = this.readVersions.get(e.toString());\n return !this.writtenDocs.has(e.toString()) && t ? t.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(t) : Precondition.none();\n }\n /**\n * Returns the precondition for a document if the operation is an update.\n */ preconditionForUpdate(e) {\n const t = this.readVersions.get(e.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(e.toString()) && t) {\n if (t.isEqual(SnapshotVersion.min())) \n // The document doesn't exist, so fail the transaction.\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(D.INVALID_ARGUMENT, \"Can't update a document that doesn't exist.\");\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(t);\n }\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(!0);\n }\n write(e) {\n this.ensureCommitNotCalled(), this.mutations.push(e);\n }\n ensureCommitNotCalled() {}\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */ class __PRIVATE_TransactionRunner {\n constructor(e, t, n, r, i) {\n this.asyncQueue = e, this.datastore = t, this.options = n, this.updateFunction = r, \n this.deferred = i, this.Ja = n.maxAttempts, this.jo = new __PRIVATE_ExponentialBackoff(this.asyncQueue, \"transaction_retry\" /* TimerId.TransactionRetry */);\n }\n /** Runs the transaction and sets the result on deferred. */ Ya() {\n this.Ja -= 1, this.Za();\n }\n Za() {\n this.jo.qo((async () => {\n const e = new Transaction$2(this.datastore), t = this.Xa(e);\n t && t.then((t => {\n this.asyncQueue.enqueueAndForget((() => e.commit().then((() => {\n this.deferred.resolve(t);\n })).catch((e => {\n this.eu(e);\n }))));\n })).catch((e => {\n this.eu(e);\n }));\n }));\n }\n Xa(e) {\n try {\n const t = this.updateFunction(e);\n return !__PRIVATE_isNullOrUndefined(t) && t.catch && t.then ? t : (this.deferred.reject(Error(\"Transaction callback must return a Promise\")), \n null);\n } catch (e) {\n // Do not retry errors thrown by user provided updateFunction.\n return this.deferred.reject(e), null;\n }\n }\n eu(e) {\n this.Ja > 0 && this.tu(e) ? (this.Ja -= 1, this.asyncQueue.enqueueAndForget((() => (this.Za(), \n Promise.resolve())))) : this.deferred.reject(e);\n }\n tu(e) {\n if (\"FirebaseError\" === e.name) {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const t = e.code;\n return \"aborted\" === t || \"failed-precondition\" === t || \"already-exists\" === t || !__PRIVATE_isPermanentError(t);\n }\n return !1;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the //\n * pieces of the client SDK architecture. It is responsible for creating the //\n * async queue that is shared by all of the other components in the system. //\n */\nclass FirestoreClient {\n constructor(e, t, \n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n n, r) {\n this.authCredentials = e, this.appCheckCredentials = t, this.asyncQueue = n, this.databaseInfo = r, \n this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.newId(), this.authCredentialListener = () => Promise.resolve(), \n this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async e => {\n __PRIVATE_logDebug(\"FirestoreClient\", \"Received user=\", e.uid), await this.authCredentialListener(e), \n this.user = e;\n })), this.appCheckCredentials.start(n, (e => (__PRIVATE_logDebug(\"FirestoreClient\", \"Received new app check token=\", e), \n this.appCheckCredentialListener(e, this.user))));\n }\n get configuration() {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: 100\n };\n }\n setCredentialChangeListener(e) {\n this.authCredentialListener = e;\n }\n setAppCheckTokenChangeListener(e) {\n this.appCheckCredentialListener = e;\n }\n /**\n * Checks that the client has not been terminated. Ensures that other methods on //\n * this class cannot be called after the client is terminated. //\n */ verifyNotTerminated() {\n if (this.asyncQueue.isShuttingDown) throw new FirestoreError(D.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n terminate() {\n this.asyncQueue.enterRestrictedMode();\n const e = new __PRIVATE_Deferred;\n return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), \n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e.resolve();\n } catch (t) {\n const n = __PRIVATE_wrapInUserErrorIfRecoverable(t, \"Failed to shutdown persistence\");\n e.reject(n);\n }\n })), e.promise;\n }\n}\n\nasync function __PRIVATE_setOfflineComponentProvider(e, t) {\n e.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(\"FirestoreClient\", \"Initializing OfflineComponentProvider\");\n const n = e.configuration;\n await t.initialize(n);\n let r = n.initialUser;\n e.setCredentialChangeListener((async e => {\n r.isEqual(e) || (await __PRIVATE_localStoreHandleUserChange(t.localStore, e), r = e);\n })), \n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n t.persistence.setDatabaseDeletedListener((() => e.terminate())), e._offlineComponents = t;\n}\n\nasync function __PRIVATE_setOnlineComponentProvider(e, t) {\n e.asyncQueue.verifyOperationInProgress();\n const n = await __PRIVATE_ensureOfflineComponents(e);\n __PRIVATE_logDebug(\"FirestoreClient\", \"Initializing OnlineComponentProvider\"), await t.initialize(n, e.configuration), \n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n e.setCredentialChangeListener((e => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, e))), \n e.setAppCheckTokenChangeListener(((e, n) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, n))), \n e._onlineComponents = t;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */ function __PRIVATE_canFallbackFromIndexedDbError(e) {\n return \"FirebaseError\" === e.name ? e.code === D.FAILED_PRECONDITION || e.code === D.UNIMPLEMENTED : !(\"undefined\" != typeof DOMException && e instanceof DOMException) || (\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n 22 === e.code || 20 === e.code || \n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n 11 === e.code);\n}\n\nasync function __PRIVATE_ensureOfflineComponents(e) {\n if (!e._offlineComponents) if (e._uninitializedComponentsProvider) {\n __PRIVATE_logDebug(\"FirestoreClient\", \"Using user provided OfflineComponentProvider\");\n try {\n await __PRIVATE_setOfflineComponentProvider(e, e._uninitializedComponentsProvider._offline);\n } catch (t) {\n const n = t;\n if (!__PRIVATE_canFallbackFromIndexedDbError(n)) throw n;\n __PRIVATE_logWarn(\"Error using user provided cache. Falling back to memory cache: \" + n), \n await __PRIVATE_setOfflineComponentProvider(e, new MemoryOfflineComponentProvider);\n }\n } else __PRIVATE_logDebug(\"FirestoreClient\", \"Using default OfflineComponentProvider\"), \n await __PRIVATE_setOfflineComponentProvider(e, new MemoryOfflineComponentProvider);\n return e._offlineComponents;\n}\n\nasync function __PRIVATE_ensureOnlineComponents(e) {\n return e._onlineComponents || (e._uninitializedComponentsProvider ? (__PRIVATE_logDebug(\"FirestoreClient\", \"Using user provided OnlineComponentProvider\"), \n await __PRIVATE_setOnlineComponentProvider(e, e._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(\"FirestoreClient\", \"Using default OnlineComponentProvider\"), \n await __PRIVATE_setOnlineComponentProvider(e, new OnlineComponentProvider))), e._onlineComponents;\n}\n\nfunction __PRIVATE_getPersistence(e) {\n return __PRIVATE_ensureOfflineComponents(e).then((e => e.persistence));\n}\n\nfunction __PRIVATE_getLocalStore(e) {\n return __PRIVATE_ensureOfflineComponents(e).then((e => e.localStore));\n}\n\nfunction __PRIVATE_getRemoteStore(e) {\n return __PRIVATE_ensureOnlineComponents(e).then((e => e.remoteStore));\n}\n\nfunction __PRIVATE_getSyncEngine(e) {\n return __PRIVATE_ensureOnlineComponents(e).then((e => e.syncEngine));\n}\n\nfunction __PRIVATE_getDatastore(e) {\n return __PRIVATE_ensureOnlineComponents(e).then((e => e.datastore));\n}\n\nasync function __PRIVATE_getEventManager(e) {\n const t = await __PRIVATE_ensureOnlineComponents(e), n = t.eventManager;\n return n.onListen = __PRIVATE_syncEngineListen.bind(null, t.syncEngine), n.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t.syncEngine), \n n.onFirstRemoteStoreListen = __PRIVATE_triggerRemoteStoreListen.bind(null, t.syncEngine), \n n.onLastRemoteStoreUnlisten = __PRIVATE_triggerRemoteStoreUnlisten.bind(null, t.syncEngine), \n n;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */ function __PRIVATE_firestoreClientEnableNetwork(e) {\n return e.asyncQueue.enqueue((async () => {\n const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);\n return t.setNetworkEnabled(!0), function __PRIVATE_remoteStoreEnableNetwork(e) {\n const t = __PRIVATE_debugCast(e);\n return t.v_.delete(0 /* OfflineCause.UserDisabled */), __PRIVATE_enableNetworkInternal(t);\n }(n);\n }));\n}\n\n/** Disables the network connection. Pending operations will not complete. */ function __PRIVATE_firestoreClientDisableNetwork(e) {\n return e.asyncQueue.enqueue((async () => {\n const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);\n return t.setNetworkEnabled(!1), async function __PRIVATE_remoteStoreDisableNetwork(e) {\n const t = __PRIVATE_debugCast(e);\n t.v_.add(0 /* OfflineCause.UserDisabled */), await __PRIVATE_disableNetworkInternal(t), \n // Set the OnlineState to Offline so get()s return from cache, etc.\n t.x_.set(\"Offline\" /* OnlineState.Offline */);\n }(n);\n }));\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */ function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e, t) {\n const n = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_readDocumentFromCache(e, t, n) {\n try {\n const r = await function __PRIVATE_localStoreReadDocument(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"read document\", \"readonly\", (e => n.localDocuments.getDocument(e, t)));\n }(e, t);\n r.isFoundDocument() ? n.resolve(r) : r.isNoDocument() ? n.resolve(null) : n.reject(new FirestoreError(D.UNAVAILABLE, \"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)\"));\n } catch (e) {\n const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to get document '${t} from cache`);\n n.reject(r);\n }\n }\n /**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e, t, n = {}) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_readDocumentViaSnapshotListener(e, t, n, r, i) {\n const s = new __PRIVATE_AsyncObserver({\n next: s => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o)));\n const _ = s.docs.has(n);\n !_ && s.fromCache ? \n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n i.reject(new FirestoreError(D.UNAVAILABLE, \"Failed to get document because the client is offline.\")) : _ && s.fromCache && r && \"server\" === r.source ? i.reject(new FirestoreError(D.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to \"server\" to retrieve the cached document.)')) : i.resolve(s);\n },\n error: e => i.reject(e)\n }), o = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n.path), s, {\n includeMetadataChanges: !0,\n ta: !0\n });\n return __PRIVATE_eventManagerListen(e, o);\n }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e, t) {\n const n = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_executeQueryFromCache(e, t, n) {\n try {\n const r = await __PRIVATE_localStoreExecuteQuery(e, t, \n /* usePreviousResults= */ !0), i = new __PRIVATE_View(t, r.hs), s = i.Ta(r.documents), o = i.applyChanges(s, \n /* limboResolutionEnabled= */ !1);\n n.resolve(o.snapshot);\n } catch (e) {\n const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to execute query '${t} against cache`);\n n.reject(r);\n }\n }\n /**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e, t, n = {}) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_executeQueryViaSnapshotListener(e, t, n, r, i) {\n const s = new __PRIVATE_AsyncObserver({\n next: n => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))), n.fromCache && \"server\" === r.source ? i.reject(new FirestoreError(D.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to \"server\" to retrieve the cached documents.)')) : i.resolve(n);\n },\n error: e => i.reject(e)\n }), o = new __PRIVATE_QueryListener(n, s, {\n includeMetadataChanges: !0,\n ta: !0\n });\n return __PRIVATE_eventManagerListen(e, o);\n }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise;\n}\n\nfunction __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e, t) {\n const n = new __PRIVATE_AsyncObserver(t);\n return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_addSnapshotsInSyncListener(e, t) {\n __PRIVATE_debugCast(e).W_.add(t), \n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n t.next();\n }(await __PRIVATE_getEventManager(e), n))), () => {\n n.Qa(), e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_removeSnapshotsInSyncListener(e, t) {\n __PRIVATE_debugCast(e).W_.delete(t);\n }(await __PRIVATE_getEventManager(e), n)));\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */ function __PRIVATE_firestoreClientLoadBundle(e, t, n, r) {\n const i = function __PRIVATE_createBundleReader(e, t) {\n let n;\n n = \"string\" == typeof e ? __PRIVATE_newTextEncoder().encode(e) : e;\n return function __PRIVATE_newBundleReader(e, t) {\n return new __PRIVATE_BundleReaderImpl(e, t);\n }(function __PRIVATE_toByteStreamReader(e, t) {\n if (e instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e, t);\n if (e instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e), t);\n if (e instanceof ReadableStream) return e.getReader();\n throw new Error(\"Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream\");\n }(n), t);\n }(n, __PRIVATE_newSerializer(t));\n e.asyncQueue.enqueueAndForget((async () => {\n __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e), i, r);\n }));\n}\n\nfunction __PRIVATE_firestoreClientGetNamedQuery(e, t) {\n return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreGetNamedQuery(e, t) {\n const n = __PRIVATE_debugCast(e);\n return n.persistence.runTransaction(\"Get named query\", \"readonly\", (e => n.$r.getNamedQuery(e, t)));\n }(await __PRIVATE_getLocalStore(e), t)));\n}\n\nfunction __PRIVATE_firestoreClientSetIndexConfiguration(e, t) {\n return e.asyncQueue.enqueue((async () => async function __PRIVATE_localStoreConfigureFieldIndexes(e, t) {\n const n = __PRIVATE_debugCast(e), r = n.indexManager, i = [];\n return n.persistence.runTransaction(\"Configure indexes\", \"readwrite\", (e => r.getFieldIndexes(e).next((n => \n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n function __PRIVATE_diffArrays(e, t, n, r, i) {\n e = [ ...e ], t = [ ...t ], e.sort(n), t.sort(n);\n const s = e.length, o = t.length;\n let _ = 0, a = 0;\n for (;_ < o && a < s; ) {\n const s = n(e[a], t[_]);\n s < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n i(e[a++]) : s > 0 ? \n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n r(t[_++]) : (_++, a++);\n }\n for (;_ < o; ) r(t[_++]);\n for (;a < s; ) i(e[a++]);\n }(n, t, __PRIVATE_fieldIndexSemanticComparator, (t => {\n i.push(r.addFieldIndex(e, t));\n }), (t => {\n i.push(r.deleteFieldIndex(e, t));\n })))).next((() => PersistencePromise.waitFor(i)))));\n }(await __PRIVATE_getLocalStore(e), t)));\n}\n\nfunction __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e, t) {\n return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e, t) {\n __PRIVATE_debugCast(e).ts.Ui = t;\n }(await __PRIVATE_getLocalStore(e), t)));\n}\n\nfunction __PRIVATE_firestoreClientDeleteAllFieldIndexes(e) {\n return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreDeleteAllFieldIndexes(e) {\n const t = __PRIVATE_debugCast(e), n = t.indexManager;\n return t.persistence.runTransaction(\"Delete All Indexes\", \"readwrite\", (e => n.deleteAllFieldIndexes(e)));\n }\n /**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // The format of the LocalStorage key that stores the client state is:\n // firestore_clients__\n (await __PRIVATE_getLocalStore(e))));\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nfunction __PRIVATE_cloneLongPollingOptions(e) {\n const t = {};\n return void 0 !== e.timeoutSeconds && (t.timeoutSeconds = e.timeoutSeconds), t;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const ge = new Map;\n\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction __PRIVATE_validateNonEmptyArgument(e, t, n) {\n if (!n) throw new FirestoreError(D.INVALID_ARGUMENT, `Function ${e}() cannot be called with an empty ${t}.`);\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */ function __PRIVATE_validateIsNotUsedTogether(e, t, n, r) {\n if (!0 === t && !0 === r) throw new FirestoreError(D.INVALID_ARGUMENT, `${e} and ${n} cannot be used together.`);\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */ function __PRIVATE_validateDocumentPath(e) {\n if (!DocumentKey.isDocumentKey(e)) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`);\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */ function __PRIVATE_validateCollectionPath(e) {\n if (DocumentKey.isDocumentKey(e)) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`);\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\n/** Returns a string describing the type / value of the provided input. */\nfunction __PRIVATE_valueDescription(e) {\n if (void 0 === e) return \"undefined\";\n if (null === e) return \"null\";\n if (\"string\" == typeof e) return e.length > 20 && (e = `${e.substring(0, 20)}...`), \n JSON.stringify(e);\n if (\"number\" == typeof e || \"boolean\" == typeof e) return \"\" + e;\n if (\"object\" == typeof e) {\n if (e instanceof Array) return \"an array\";\n {\n const t = \n /** try to get the constructor name for an object. */\n function __PRIVATE_tryGetCustomObjectType(e) {\n if (e.constructor) return e.constructor.name;\n return null;\n }\n /**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */ (e);\n return t ? `a custom ${t} object` : \"an object\";\n }\n }\n return \"function\" == typeof e ? \"a function\" : fail();\n}\n\nfunction __PRIVATE_cast(e, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nt) {\n if (\"_delegate\" in e && (\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n e = e._delegate), !(e instanceof t)) {\n if (t.name === e.constructor.name) throw new FirestoreError(D.INVALID_ARGUMENT, \"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?\");\n {\n const n = __PRIVATE_valueDescription(e);\n throw new FirestoreError(D.INVALID_ARGUMENT, `Expected type '${t.name}', but it was: ${n}`);\n }\n }\n return e;\n}\n\nfunction __PRIVATE_validatePositiveNumber(e, t) {\n if (t <= 0) throw new FirestoreError(D.INVALID_ARGUMENT, `Function ${e}() requires a positive number, but it was: ${t}.`);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// settings() defaults:\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass FirestoreSettingsImpl {\n constructor(e) {\n var t, n;\n if (void 0 === e.host) {\n if (void 0 !== e.ssl) throw new FirestoreError(D.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n this.host = \"firestore.googleapis.com\", this.ssl = true;\n } else this.host = e.host, this.ssl = null === (t = e.ssl) || void 0 === t || t;\n if (this.credentials = e.credentials, this.ignoreUndefinedProperties = !!e.ignoreUndefinedProperties, \n this.localCache = e.localCache, void 0 === e.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {\n if (-1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new FirestoreError(D.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n this.cacheSizeBytes = e.cacheSizeBytes;\n }\n __PRIVATE_validateIsNotUsedTogether(\"experimentalForceLongPolling\", e.experimentalForceLongPolling, \"experimentalAutoDetectLongPolling\", e.experimentalAutoDetectLongPolling), \n this.experimentalForceLongPolling = !!e.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === e.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : \n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling = !!e.experimentalAutoDetectLongPolling, \n this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(null !== (n = e.experimentalLongPollingOptions) && void 0 !== n ? n : {}), \n function __PRIVATE_validateLongPollingOptions(e) {\n if (void 0 !== e.timeoutSeconds) {\n if (isNaN(e.timeoutSeconds)) throw new FirestoreError(D.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);\n if (e.timeoutSeconds < 5) throw new FirestoreError(D.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);\n if (e.timeoutSeconds > 30) throw new FirestoreError(D.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`);\n }\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!e.useFetchStreams;\n }\n isEqual(e) {\n return this.host === e.host && this.ssl === e.ssl && this.credentials === e.credentials && this.cacheSizeBytes === e.cacheSizeBytes && this.experimentalForceLongPolling === e.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(e, t) {\n return e.timeoutSeconds === t.timeoutSeconds;\n }(this.experimentalLongPollingOptions, e.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e.ignoreUndefinedProperties && this.useFetchStreams === e.useFetchStreams;\n }\n}\n\nclass Firestore$1 {\n /** @hideconstructor */\n constructor(e, t, n, r) {\n this._authCredentials = e, this._appCheckCredentials = t, this._databaseId = n, \n this._app = r, \n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n this.type = \"firestore-lite\", this._persistenceKey = \"(lite)\", this._settings = new FirestoreSettingsImpl({}), \n this._settingsFrozen = !1;\n }\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */ get app() {\n if (!this._app) throw new FirestoreError(D.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is not available\");\n return this._app;\n }\n get _initialized() {\n return this._settingsFrozen;\n }\n get _terminated() {\n return void 0 !== this._terminateTask;\n }\n _setSettings(e) {\n if (this._settingsFrozen) throw new FirestoreError(D.FAILED_PRECONDITION, \"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.\");\n this._settings = new FirestoreSettingsImpl(e), void 0 !== e.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(e) {\n if (!e) return new __PRIVATE_EmptyAuthCredentialsProvider;\n switch (e.type) {\n case \"firstParty\":\n return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex || \"0\", e.iamToken || null, e.authTokenFactory || null);\n\n case \"provider\":\n return e.client;\n\n default:\n throw new FirestoreError(D.INVALID_ARGUMENT, \"makeAuthCredentialsProvider failed due to invalid credential type\");\n }\n }(e.credentials));\n }\n _getSettings() {\n return this._settings;\n }\n _freezeSettings() {\n return this._settingsFrozen = !0, this._settings;\n }\n _delete() {\n return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;\n }\n /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */ _terminate() {\n /**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\n return function __PRIVATE_removeComponents(e) {\n const t = ge.get(e);\n t && (__PRIVATE_logDebug(\"ComponentProvider\", \"Removing Datastore\"), ge.delete(e), \n t.terminate());\n }(this), Promise.resolve();\n }\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */ function connectFirestoreEmulator(e, t, n, r = {}) {\n var i;\n const s = (e = __PRIVATE_cast(e, Firestore$1))._getSettings(), o = `${t}:${n}`;\n if (\"firestore.googleapis.com\" !== s.host && s.host !== o && __PRIVATE_logWarn(\"Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.\"), \n e._setSettings(Object.assign(Object.assign({}, s), {\n host: o,\n ssl: !1\n })), r.mockUserToken) {\n let t, n;\n if (\"string\" == typeof r.mockUserToken) t = r.mockUserToken, n = User.MOCK_USER; else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n t = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.createMockUserToken)(r.mockUserToken, null === (i = e._app) || void 0 === i ? void 0 : i.options.projectId);\n const s = r.mockUserToken.sub || r.mockUserToken.user_id;\n if (!s) throw new FirestoreError(D.INVALID_ARGUMENT, \"mockUserToken must contain 'sub' or 'user_id' field!\");\n n = new User(s);\n }\n e._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t, n));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */ class Query {\n // This is the lite version of the Query class in the main SDK.\n /** @hideconstructor protected */\n constructor(e, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n t, n) {\n this.converter = t, this._query = n, \n /** The type of this Firestore reference. */\n this.type = \"query\", this.firestore = e;\n }\n withConverter(e) {\n return new Query(this.firestore, e, this._query);\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */ class DocumentReference {\n /** @hideconstructor */\n constructor(e, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n t, n) {\n this.converter = t, this._key = n, \n /** The type of this Firestore reference. */\n this.type = \"document\", this.firestore = e;\n }\n get _path() {\n return this._key.path;\n }\n /**\n * The document's identifier within its collection.\n */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */ get path() {\n return this._key.path.canonicalString();\n }\n /**\n * The collection this `DocumentReference` belongs to.\n */ get parent() {\n return new CollectionReference(this.firestore, this.converter, this._key.path.popLast());\n }\n withConverter(e) {\n return new DocumentReference(this.firestore, e, this._key);\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */ class CollectionReference extends Query {\n /** @hideconstructor */\n constructor(e, t, n) {\n super(e, t, __PRIVATE_newQueryForPath(n)), this._path = n, \n /** The type of this Firestore reference. */\n this.type = \"collection\";\n }\n /** The collection's identifier. */ get id() {\n return this._query.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */ get path() {\n return this._query.path.canonicalString();\n }\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */ get parent() {\n const e = this._path.popLast();\n return e.isEmpty() ? null : new DocumentReference(this.firestore, \n /* converter= */ null, new DocumentKey(e));\n }\n withConverter(e) {\n return new CollectionReference(this.firestore, e, this._path);\n }\n}\n\nfunction collection(e, t, ...n) {\n if (e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(e), __PRIVATE_validateNonEmptyArgument(\"collection\", \"path\", t), e instanceof Firestore$1) {\n const r = ResourcePath.fromString(t, ...n);\n return __PRIVATE_validateCollectionPath(r), new CollectionReference(e, /* converter= */ null, r);\n }\n {\n if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(D.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const r = e._path.child(ResourcePath.fromString(t, ...n));\n return __PRIVATE_validateCollectionPath(r), new CollectionReference(e.firestore, \n /* converter= */ null, r);\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */ function collectionGroup(e, t) {\n if (e = __PRIVATE_cast(e, Firestore$1), __PRIVATE_validateNonEmptyArgument(\"collectionGroup\", \"collection id\", t), \n t.indexOf(\"/\") >= 0) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);\n return new Query(e, \n /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(e) {\n return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e);\n }(t));\n}\n\nfunction doc(e, t, ...n) {\n if (e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(e), \n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n 1 === arguments.length && (t = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument(\"doc\", \"path\", t), \n e instanceof Firestore$1) {\n const r = ResourcePath.fromString(t, ...n);\n return __PRIVATE_validateDocumentPath(r), new DocumentReference(e, \n /* converter= */ null, new DocumentKey(r));\n }\n {\n if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(D.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const r = e._path.child(ResourcePath.fromString(t, ...n));\n return __PRIVATE_validateDocumentPath(r), new DocumentReference(e.firestore, e instanceof CollectionReference ? e.converter : null, new DocumentKey(r));\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function refEqual(e, t) {\n return e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(e), t = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(t), (e instanceof DocumentReference || e instanceof CollectionReference) && (t instanceof DocumentReference || t instanceof CollectionReference) && (e.firestore === t.firestore && e.path === t.path && e.converter === t.converter);\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function queryEqual(e, t) {\n return e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(e), t = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(t), e instanceof Query && t instanceof Query && (e.firestore === t.firestore && __PRIVATE_queryEquals(e._query, t._query) && e.converter === t.converter);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_AsyncQueueImpl {\n constructor() {\n // The last promise in the queue.\n this.nu = Promise.resolve(), \n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n this.ru = [], \n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n this.iu = !1, \n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n this.su = [], \n // visible for testing\n this.ou = null, \n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this._u = !1, \n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n this.au = !1, \n // List of TimerIds to fast-forward delays for.\n this.uu = [], \n // Backoff timer used to schedule retries for retryable operations\n this.jo = new __PRIVATE_ExponentialBackoff(this, \"async_queue_retry\" /* TimerId.AsyncQueueRetry */), \n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n this.cu = () => {\n const e = getDocument();\n e && __PRIVATE_logDebug(\"AsyncQueue\", \"Visibility state changed to \" + e.visibilityState), \n this.jo.Ko();\n };\n const e = getDocument();\n e && \"function\" == typeof e.addEventListener && e.addEventListener(\"visibilitychange\", this.cu);\n }\n get isShuttingDown() {\n return this.iu;\n }\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */ enqueueAndForget(e) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(e);\n }\n enqueueAndForgetEvenWhileRestricted(e) {\n this.lu(), \n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.hu(e);\n }\n enterRestrictedMode(e) {\n if (!this.iu) {\n this.iu = !0, this.au = e || !1;\n const t = getDocument();\n t && \"function\" == typeof t.removeEventListener && t.removeEventListener(\"visibilitychange\", this.cu);\n }\n }\n enqueue(e) {\n if (this.lu(), this.iu) \n // Return a Promise which never resolves.\n return new Promise((() => {}));\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const t = new __PRIVATE_Deferred;\n return this.hu((() => this.iu && this.au ? Promise.resolve() : (e().then(t.resolve, t.reject), \n t.promise))).then((() => t.promise));\n }\n enqueueRetryable(e) {\n this.enqueueAndForget((() => (this.ru.push(e), this.Pu())));\n }\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */ async Pu() {\n if (0 !== this.ru.length) {\n try {\n await this.ru[0](), this.ru.shift(), this.jo.reset();\n } catch (e) {\n if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n // Failure will be handled by AsyncQueue\n __PRIVATE_logDebug(\"AsyncQueue\", \"Operation failed with retryable error: \" + e);\n }\n this.ru.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.jo.qo((() => this.Pu()));\n }\n }\n hu(e) {\n const t = this.nu.then((() => (this._u = !0, e().catch((e => {\n this.ou = e, this._u = !1;\n const t = \n /**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\n function __PRIVATE_getMessageOrStack(e) {\n let t = e.message || \"\";\n e.stack && (t = e.stack.includes(e.message) ? e.stack : e.message + \"\\n\" + e.stack);\n return t;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (e);\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw __PRIVATE_logError(\"INTERNAL UNHANDLED ERROR: \", t), e;\n })).then((e => (this._u = !1, e))))));\n return this.nu = t, t;\n }\n enqueueAfterDelay(e, t, n) {\n this.lu(), \n // Fast-forward delays for timerIds that have been overriden.\n this.uu.indexOf(e) > -1 && (t = 0);\n const r = DelayedOperation.createAndSchedule(this, e, t, n, (e => this.Iu(e)));\n return this.su.push(r), r;\n }\n lu() {\n this.ou && fail();\n }\n verifyOperationInProgress() {}\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */ async Tu() {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let e;\n do {\n e = this.nu, await e;\n } while (e !== this.nu);\n }\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */ Eu(e) {\n for (const t of this.su) if (t.timerId === e) return !0;\n return !1;\n }\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */ du(e) {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.Tu().then((() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.su.sort(((e, t) => e.targetTimeMs - t.targetTimeMs));\n for (const t of this.su) if (t.skipDelay(), \"all\" /* TimerId.All */ !== e && t.timerId === e) break;\n return this.Tu();\n }));\n }\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */ Au(e) {\n this.uu.push(e);\n }\n /** Called once a DelayedOperation is run or canceled. */ Iu(e) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const t = this.su.indexOf(e);\n this.su.splice(t, 1);\n }\n}\n\nfunction __PRIVATE_isPartialObserver(e) {\n /**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\n return function __PRIVATE_implementsAnyMethods(e, t) {\n if (\"object\" != typeof e || null === e) return !1;\n const n = e;\n for (const e of t) if (e in n && \"function\" == typeof n[e]) return !0;\n return !1;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */ (e, [ \"next\", \"error\", \"complete\" ]);\n}\n\nclass LoadBundleTask {\n constructor() {\n this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred, \n this._lastProgress = {\n taskState: \"Running\",\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n }\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */ onProgress(e, t, n) {\n this._progressObserver = {\n next: e,\n error: t,\n complete: n\n };\n }\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */ catch(e) {\n return this._taskCompletionResolver.promise.catch(e);\n }\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */ then(e, t) {\n return this._taskCompletionResolver.promise.then(e, t);\n }\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */ _completeWith(e) {\n this._updateProgress(e), this._progressObserver.complete && this._progressObserver.complete(), \n this._taskCompletionResolver.resolve(e);\n }\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */ _failWith(e) {\n this._lastProgress.taskState = \"Error\", this._progressObserver.next && this._progressObserver.next(this._lastProgress), \n this._progressObserver.error && this._progressObserver.error(e), this._taskCompletionResolver.reject(e);\n }\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */ _updateProgress(e) {\n this._lastProgress = e, this._progressObserver.next && this._progressObserver.next(e);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * {@link Firestore} instance.\n */ const pe = -1;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ class Firestore extends Firestore$1 {\n /** @hideconstructor */\n constructor(e, t, n, r) {\n super(e, t, n, r), \n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n this.type = \"firestore\", this._queue = function __PRIVATE_newAsyncQueue() {\n return new __PRIVATE_AsyncQueueImpl;\n }(), this._persistenceKey = (null == r ? void 0 : r.name) || \"[DEFAULT]\";\n }\n _terminate() {\n return this._firestoreClient || \n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n __PRIVATE_configureFirestore(this), this._firestoreClient.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */ function initializeFirestore(e, t, n) {\n n || (n = \"(default)\");\n const r = (0,_firebase_app__WEBPACK_IMPORTED_MODULE_0__._getProvider)(e, \"firestore\");\n if (r.isInitialized(n)) {\n const e = r.getImmediate({\n identifier: n\n }), i = r.getOptions(n);\n if ((0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.deepEqual)(i, t)) return e;\n throw new FirestoreError(D.FAILED_PRECONDITION, \"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.\");\n }\n if (void 0 !== t.cacheSizeBytes && void 0 !== t.localCache) throw new FirestoreError(D.INVALID_ARGUMENT, \"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object\");\n if (void 0 !== t.cacheSizeBytes && -1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new FirestoreError(D.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n return r.initialize({\n options: t,\n instanceIdentifier: n\n });\n}\n\nfunction getFirestore(t, n) {\n const r = \"object\" == typeof t ? t : (0,_firebase_app__WEBPACK_IMPORTED_MODULE_0__.getApp)(), i = \"string\" == typeof t ? t : n || \"(default)\", s = (0,_firebase_app__WEBPACK_IMPORTED_MODULE_0__._getProvider)(r, \"firestore\").getImmediate({\n identifier: i\n });\n if (!s._initialized) {\n const e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getDefaultEmulatorHostnameAndPort)(\"firestore\");\n e && connectFirestoreEmulator(s, ...e);\n }\n return s;\n}\n\n/**\n * @internal\n */ function ensureFirestoreConfigured(e) {\n return e._firestoreClient || __PRIVATE_configureFirestore(e), e._firestoreClient.verifyNotTerminated(), \n e._firestoreClient;\n}\n\nfunction __PRIVATE_configureFirestore(e) {\n var t, n, r;\n const i = e._freezeSettings(), s = function __PRIVATE_makeDatabaseInfo(e, t, n, r) {\n return new DatabaseInfo(e, t, n, r.host, r.ssl, r.experimentalForceLongPolling, r.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(r.experimentalLongPollingOptions), r.useFetchStreams);\n }(e._databaseId, (null === (t = e._app) || void 0 === t ? void 0 : t.options.appId) || \"\", e._persistenceKey, i);\n e._firestoreClient = new FirestoreClient(e._authCredentials, e._appCheckCredentials, e._queue, s), \n (null === (n = i.localCache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (r = i.localCache) || void 0 === r ? void 0 : r._onlineComponentProvider) && (e._firestoreClient._uninitializedComponentsProvider = {\n _offlineKind: i.localCache.kind,\n _offline: i.localCache._offlineComponentProvider,\n _online: i.localCache._onlineComponentProvider\n });\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * On failure, `enableIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * Note: `enableIndexedDbPersistence()` must be called before any other functions\n * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */ function enableIndexedDbPersistence(e, t) {\n __PRIVATE_verifyNotInitialized(e = __PRIVATE_cast(e, Firestore));\n const n = ensureFirestoreConfigured(e);\n if (n._uninitializedComponentsProvider) throw new FirestoreError(D.FAILED_PRECONDITION, \"SDK cache is already specified.\");\n __PRIVATE_logWarn(\"enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.\");\n const r = e._freezeSettings(), i = new OnlineComponentProvider;\n return __PRIVATE_setPersistenceProviders(n, i, new __PRIVATE_IndexedDbOfflineComponentProvider(i, r.cacheSizeBytes, null == t ? void 0 : t.forceOwnership));\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */ function enableMultiTabIndexedDbPersistence(e) {\n __PRIVATE_verifyNotInitialized(e = __PRIVATE_cast(e, Firestore));\n const t = ensureFirestoreConfigured(e);\n if (t._uninitializedComponentsProvider) throw new FirestoreError(D.FAILED_PRECONDITION, \"SDK cache is already specified.\");\n __PRIVATE_logWarn(\"enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.\");\n const n = e._freezeSettings(), r = new OnlineComponentProvider;\n return __PRIVATE_setPersistenceProviders(t, r, new __PRIVATE_MultiTabOfflineComponentProvider(r, n.cacheSizeBytes));\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */ function __PRIVATE_setPersistenceProviders(e, t, n) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueue((async () => {\n try {\n await __PRIVATE_setOfflineComponentProvider(e, n), await __PRIVATE_setOnlineComponentProvider(e, t), \n r.resolve();\n } catch (e) {\n const t = e;\n if (!__PRIVATE_canFallbackFromIndexedDbError(t)) throw t;\n __PRIVATE_logWarn(\"Error enabling indexeddb cache. Falling back to memory cache: \" + t), \n r.reject(t);\n }\n })).then((() => r.promise));\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */ function clearIndexedDbPersistence(e) {\n if (e._initialized && !e._terminated) throw new FirestoreError(D.FAILED_PRECONDITION, \"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.\");\n const t = new __PRIVATE_Deferred;\n return e._queue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n await async function __PRIVATE_indexedDbClearPersistence(e) {\n if (!__PRIVATE_SimpleDb.D()) return Promise.resolve();\n const t = e + \"main\";\n await __PRIVATE_SimpleDb.delete(t);\n }(__PRIVATE_indexedDbStoragePrefix(e._databaseId, e._persistenceKey)), t.resolve();\n } catch (e) {\n t.reject(e);\n }\n })), t.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */ function waitForPendingWrites(e) {\n return function __PRIVATE_firestoreClientWaitForPendingWrites(e) {\n const t = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e), t))), \n t.promise;\n }(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */ function enableNetwork(e) {\n return __PRIVATE_firestoreClientEnableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */ function disableNetwork(e) {\n return __PRIVATE_firestoreClientDisableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */ function terminate(e) {\n return (0,_firebase_app__WEBPACK_IMPORTED_MODULE_0__._removeServiceInstance)(e.app, \"firestore\", e._databaseId.database), e._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise`.\n */ function loadBundle(e, t) {\n const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), r = new LoadBundleTask;\n return __PRIVATE_firestoreClientLoadBundle(n, e._databaseId, t, r), r;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */ function namedQuery(e, t) {\n return __PRIVATE_firestoreClientGetNamedQuery(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), t).then((t => t ? new Query(e, null, t.query) : null));\n}\n\nfunction __PRIVATE_verifyNotInitialized(e) {\n if (e._initialized || e._terminated) throw new FirestoreError(D.FAILED_PRECONDITION, \"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nclass AggregateField {\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(e = \"count\", t) {\n this._internalFieldPath = t, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateField\", this.aggregateType = e;\n }\n}\n\n/**\n * The results of executing an aggregation query.\n */ class AggregateQuerySnapshot {\n /** @hideconstructor */\n constructor(e, t, n) {\n this._userDataWriter = t, this._data = n, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateQuerySnapshot\", this.query = e;\n }\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */ data() {\n return this._userDataWriter.convertObjectMap(this._data);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing an array of bytes.\n */ class Bytes {\n /** @hideconstructor */\n constructor(e) {\n this._byteString = e;\n }\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */ static fromBase64String(e) {\n try {\n return new Bytes(ByteString.fromBase64String(e));\n } catch (e) {\n throw new FirestoreError(D.INVALID_ARGUMENT, \"Failed to construct data from Base64 string: \" + e);\n }\n }\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */ static fromUint8Array(e) {\n return new Bytes(ByteString.fromUint8Array(e));\n }\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */ toBase64() {\n return this._byteString.toBase64();\n }\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */ toUint8Array() {\n return this._byteString.toUint8Array();\n }\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */ toString() {\n return \"Bytes(base64: \" + this.toBase64() + \")\";\n }\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */ isEqual(e) {\n return this._byteString.isEqual(e._byteString);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */ class FieldPath {\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...e) {\n for (let t = 0; t < e.length; ++t) if (0 === e[t].length) throw new FirestoreError(D.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). Field names must not be empty.\");\n this._internalPath = new FieldPath$1(e);\n }\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */ isEqual(e) {\n return this._internalPath.isEqual(e._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */ function documentId() {\n return new FieldPath(\"__name__\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */ class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(e) {\n this._methodName = e;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */ class GeoPoint {\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(e, t) {\n if (!isFinite(e) || e < -90 || e > 90) throw new FirestoreError(D.INVALID_ARGUMENT, \"Latitude must be a number between -90 and 90, but was: \" + e);\n if (!isFinite(t) || t < -180 || t > 180) throw new FirestoreError(D.INVALID_ARGUMENT, \"Longitude must be a number between -180 and 180, but was: \" + t);\n this._lat = e, this._long = t;\n }\n /**\n * The latitude of this `GeoPoint` instance.\n */ get latitude() {\n return this._lat;\n }\n /**\n * The longitude of this `GeoPoint` instance.\n */ get longitude() {\n return this._long;\n }\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */ isEqual(e) {\n return this._lat === e._lat && this._long === e._long;\n }\n /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */ _compareTo(e) {\n return __PRIVATE_primitiveComparator(this._lat, e._lat) || __PRIVATE_primitiveComparator(this._long, e._long);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const ye = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData {\n constructor(e, t, n) {\n this.data = e, this.fieldMask = t, this.fieldTransforms = n;\n }\n toMutation(e, t) {\n return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms) : new __PRIVATE_SetMutation(e, this.data, t, this.fieldTransforms);\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */ class ParsedUpdateData {\n constructor(e, \n // The fieldMask does not include document transforms.\n t, n) {\n this.data = e, this.fieldMask = t, this.fieldTransforms = n;\n }\n toMutation(e, t) {\n return new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms);\n }\n}\n\nfunction __PRIVATE_isWrite(e) {\n switch (e) {\n case 0 /* UserDataSource.Set */ :\n // fall through\n case 2 /* UserDataSource.MergeSet */ :\n // fall through\n case 1 /* UserDataSource.Update */ :\n return !0;\n\n case 3 /* UserDataSource.Argument */ :\n case 4 /* UserDataSource.ArrayArgument */ :\n return !1;\n\n default:\n throw fail();\n }\n}\n\n/** A \"context\" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(e, t, n, r, i, s) {\n this.settings = e, this.databaseId = t, this.serializer = n, this.ignoreUndefinedProperties = r, \n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n void 0 === i && this.Ru(), this.fieldTransforms = i || [], this.fieldMask = s || [];\n }\n get path() {\n return this.settings.path;\n }\n get Vu() {\n return this.settings.Vu;\n }\n /** Returns a new context with the specified settings overwritten. */ mu(e) {\n return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({}, this.settings), e), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);\n }\n fu(e) {\n var t;\n const n = null === (t = this.path) || void 0 === t ? void 0 : t.child(e), r = this.mu({\n path: n,\n gu: !1\n });\n return r.pu(e), r;\n }\n yu(e) {\n var t;\n const n = null === (t = this.path) || void 0 === t ? void 0 : t.child(e), r = this.mu({\n path: n,\n gu: !1\n });\n return r.Ru(), r;\n }\n wu(e) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.mu({\n path: void 0,\n gu: !0\n });\n }\n Su(e) {\n return __PRIVATE_createError(e, this.settings.methodName, this.settings.bu || !1, this.path, this.settings.Du);\n }\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(e) {\n return void 0 !== this.fieldMask.find((t => e.isPrefixOf(t))) || void 0 !== this.fieldTransforms.find((t => e.isPrefixOf(t.field)));\n }\n Ru() {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path) for (let e = 0; e < this.path.length; e++) this.pu(this.path.get(e));\n }\n pu(e) {\n if (0 === e.length) throw this.Su(\"Document fields must not be empty\");\n if (__PRIVATE_isWrite(this.Vu) && ye.test(e)) throw this.Su('Document fields cannot begin and end with \"__\"');\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */ class __PRIVATE_UserDataReader {\n constructor(e, t, n) {\n this.databaseId = e, this.ignoreUndefinedProperties = t, this.serializer = n || __PRIVATE_newSerializer(e);\n }\n /** Creates a new top-level parse context. */ Cu(e, t, n, r = !1) {\n return new __PRIVATE_ParseContextImpl({\n Vu: e,\n methodName: t,\n Du: n,\n path: FieldPath$1.emptyPath(),\n gu: !1,\n bu: r\n }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);\n }\n}\n\nfunction __PRIVATE_newUserDataReader(e) {\n const t = e._freezeSettings(), n = __PRIVATE_newSerializer(e._databaseId);\n return new __PRIVATE_UserDataReader(e._databaseId, !!t.ignoreUndefinedProperties, n);\n}\n\n/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(e, t, n, r, i, s = {}) {\n const o = e.Cu(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , t, n, i);\n __PRIVATE_validatePlainObject(\"Data must be an object, but it was:\", o, r);\n const _ = __PRIVATE_parseObject(r, o);\n let a, u;\n if (s.merge) a = new FieldMask(o.fieldMask), u = o.fieldTransforms; else if (s.mergeFields) {\n const e = [];\n for (const r of s.mergeFields) {\n const i = __PRIVATE_fieldPathFromArgument$1(t, r, n);\n if (!o.contains(i)) throw new FirestoreError(D.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);\n __PRIVATE_fieldMaskContains(e, i) || e.push(i);\n }\n a = new FieldMask(e), u = o.fieldTransforms.filter((e => a.covers(e.field)));\n } else a = null, u = o.fieldTransforms;\n return new ParsedSetData(new ObjectValue(_), a, u);\n}\n\nclass __PRIVATE_DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(e) {\n if (2 /* UserDataSource.MergeSet */ !== e.Vu) throw 1 /* UserDataSource.Update */ === e.Vu ? e.Su(`${this._methodName}() can only appear at the top level of your update data`) : e.Su(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n return e.fieldMask.push(e.path), null;\n }\n isEqual(e) {\n return e instanceof __PRIVATE_DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */ function __PRIVATE_createSentinelChildContext(e, t, n) {\n return new __PRIVATE_ParseContextImpl({\n Vu: 3 /* UserDataSource.Argument */ ,\n Du: t.settings.Du,\n methodName: e._methodName,\n gu: n\n }, t.databaseId, t.serializer, t.ignoreUndefinedProperties);\n}\n\nclass __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(e) {\n return new FieldTransform(e.path, new __PRIVATE_ServerTimestampTransform);\n }\n isEqual(e) {\n return e instanceof __PRIVATE_ServerTimestampFieldValueImpl;\n }\n}\n\nclass __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue {\n constructor(e, t) {\n super(e), this.vu = t;\n }\n _toFieldTransform(e) {\n const t = __PRIVATE_createSentinelChildContext(this, e, \n /*array=*/ !0), n = this.vu.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayUnionTransformOperation(n);\n return new FieldTransform(e.path, r);\n }\n isEqual(e) {\n return e instanceof __PRIVATE_ArrayUnionFieldValueImpl && (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.deepEqual)(this.vu, e.vu);\n }\n}\n\nclass __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(e, t) {\n super(e), this.vu = t;\n }\n _toFieldTransform(e) {\n const t = __PRIVATE_createSentinelChildContext(this, e, \n /*array=*/ !0), n = this.vu.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayRemoveTransformOperation(n);\n return new FieldTransform(e.path, r);\n }\n isEqual(e) {\n return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl && (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.deepEqual)(this.vu, e.vu);\n }\n}\n\nclass __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue {\n constructor(e, t) {\n super(e), this.Fu = t;\n }\n _toFieldTransform(e) {\n const t = new __PRIVATE_NumericIncrementTransformOperation(e.serializer, toNumber(e.serializer, this.Fu));\n return new FieldTransform(e.path, t);\n }\n isEqual(e) {\n return e instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.Fu === e.Fu;\n }\n}\n\n/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(e, t, n, r) {\n const i = e.Cu(1 /* UserDataSource.Update */ , t, n);\n __PRIVATE_validatePlainObject(\"Data must be an object, but it was:\", i, r);\n const s = [], o = ObjectValue.empty();\n forEach(r, ((e, r) => {\n const _ = __PRIVATE_fieldPathFromDotSeparatedString(t, e, n);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n r = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(r);\n const a = i.yu(_);\n if (r instanceof __PRIVATE_DeleteFieldValueImpl) \n // Add it to the field mask, but don't add anything to updateData.\n s.push(_); else {\n const e = __PRIVATE_parseData(r, a);\n null != e && (s.push(_), o.set(_, e));\n }\n }));\n const _ = new FieldMask(s);\n return new ParsedUpdateData(o, _, i.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(e, t, n, r, i, s) {\n const o = e.Cu(1 /* UserDataSource.Update */ , t, n), _ = [ __PRIVATE_fieldPathFromArgument$1(t, r, n) ], a = [ i ];\n if (s.length % 2 != 0) throw new FirestoreError(D.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);\n for (let e = 0; e < s.length; e += 2) _.push(__PRIVATE_fieldPathFromArgument$1(t, s[e])), \n a.push(s[e + 1]);\n const u = [], c = ObjectValue.empty();\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let e = _.length - 1; e >= 0; --e) if (!__PRIVATE_fieldMaskContains(u, _[e])) {\n const t = _[e];\n let n = a[e];\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n n = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(n);\n const r = o.yu(t);\n if (n instanceof __PRIVATE_DeleteFieldValueImpl) \n // Add it to the field mask, but don't add anything to updateData.\n u.push(t); else {\n const e = __PRIVATE_parseData(n, r);\n null != e && (u.push(t), c.set(t, e));\n }\n }\n const l = new FieldMask(u);\n return new ParsedUpdateData(c, l, o.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */ function __PRIVATE_parseQueryValue(e, t, n, r = !1) {\n return __PRIVATE_parseData(n, e.Cu(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , t));\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */ function __PRIVATE_parseData(e, t) {\n if (__PRIVATE_looksLikeJsonObject(\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(e))) return __PRIVATE_validatePlainObject(\"Unsupported field value:\", t, e), \n __PRIVATE_parseObject(e, t);\n if (e instanceof FieldValue) \n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n return function __PRIVATE_parseSentinelFieldValue(e, t) {\n // Sentinels are only supported with writes, and not within arrays.\n if (!__PRIVATE_isWrite(t.Vu)) throw t.Su(`${e._methodName}() can only be used with update() and set()`);\n if (!t.path) throw t.Su(`${e._methodName}() is not currently supported inside arrays`);\n const n = e._toFieldTransform(t);\n n && t.fieldTransforms.push(n);\n }\n /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */ (e, t), null;\n if (void 0 === e && t.ignoreUndefinedProperties) \n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n if (\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n t.path && t.fieldMask.push(t.path), e instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (t.settings.gu && 4 /* UserDataSource.ArrayArgument */ !== t.Vu) throw t.Su(\"Nested arrays are not supported\");\n return function __PRIVATE_parseArray(e, t) {\n const n = [];\n let r = 0;\n for (const i of e) {\n let e = __PRIVATE_parseData(i, t.wu(r));\n null == e && (\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n e = {\n nullValue: \"NULL_VALUE\"\n }), n.push(e), r++;\n }\n return {\n arrayValue: {\n values: n\n }\n };\n }(e, t);\n }\n return function __PRIVATE_parseScalarValue(e, t) {\n if (null === (e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(e))) return {\n nullValue: \"NULL_VALUE\"\n };\n if (\"number\" == typeof e) return toNumber(t.serializer, e);\n if (\"boolean\" == typeof e) return {\n booleanValue: e\n };\n if (\"string\" == typeof e) return {\n stringValue: e\n };\n if (e instanceof Date) {\n const n = Timestamp.fromDate(e);\n return {\n timestampValue: toTimestamp(t.serializer, n)\n };\n }\n if (e instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const n = new Timestamp(e.seconds, 1e3 * Math.floor(e.nanoseconds / 1e3));\n return {\n timestampValue: toTimestamp(t.serializer, n)\n };\n }\n if (e instanceof GeoPoint) return {\n geoPointValue: {\n latitude: e.latitude,\n longitude: e.longitude\n }\n };\n if (e instanceof Bytes) return {\n bytesValue: __PRIVATE_toBytes(t.serializer, e._byteString)\n };\n if (e instanceof DocumentReference) {\n const n = t.databaseId, r = e.firestore._databaseId;\n if (!r.isEqual(n)) throw t.Su(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);\n return {\n referenceValue: __PRIVATE_toResourceName(e.firestore._databaseId || t.databaseId, e._key.path)\n };\n }\n throw t.Su(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`);\n }\n /**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */ (e, t);\n}\n\nfunction __PRIVATE_parseObject(e, t) {\n const n = {};\n return isEmpty(e) ? \n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n t.path && t.path.length > 0 && t.fieldMask.push(t.path) : forEach(e, ((e, r) => {\n const i = __PRIVATE_parseData(r, t.fu(e));\n null != i && (n[e] = i);\n })), {\n mapValue: {\n fields: n\n }\n };\n}\n\nfunction __PRIVATE_looksLikeJsonObject(e) {\n return !(\"object\" != typeof e || null === e || e instanceof Array || e instanceof Date || e instanceof Timestamp || e instanceof GeoPoint || e instanceof Bytes || e instanceof DocumentReference || e instanceof FieldValue);\n}\n\nfunction __PRIVATE_validatePlainObject(e, t, n) {\n if (!__PRIVATE_looksLikeJsonObject(n) || !function __PRIVATE_isPlainObject(e) {\n return \"object\" == typeof e && null !== e && (Object.getPrototypeOf(e) === Object.prototype || null === Object.getPrototypeOf(e));\n }(n)) {\n const r = __PRIVATE_valueDescription(n);\n throw \"an object\" === r ? t.Su(e + \" a custom object\") : t.Su(e + \" \" + r);\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */ function __PRIVATE_fieldPathFromArgument$1(e, t, n) {\n if ((\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n t = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(t)) instanceof FieldPath) return t._internalPath;\n if (\"string\" == typeof t) return __PRIVATE_fieldPathFromDotSeparatedString(e, t);\n throw __PRIVATE_createError(\"Field path arguments must be of type string or \", e, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */ const we = new RegExp(\"[~\\\\*/\\\\[\\\\]]\");\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */ function __PRIVATE_fieldPathFromDotSeparatedString(e, t, n) {\n if (t.search(we) >= 0) throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`, e, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n try {\n return new FieldPath(...t.split(\".\"))._internalPath;\n } catch (r) {\n throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, e, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n }\n}\n\nfunction __PRIVATE_createError(e, t, n, r, i) {\n const s = r && !r.isEmpty(), o = void 0 !== i;\n let _ = `Function ${t}() called with invalid data`;\n n && (_ += \" (via `toFirestore()`)\"), _ += \". \";\n let a = \"\";\n return (s || o) && (a += \" (found\", s && (a += ` in field ${r}`), o && (a += ` in document ${i}`), \n a += \")\"), new FirestoreError(D.INVALID_ARGUMENT, _ + e + a);\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(e, t) {\n return e.some((e => e.isEqual(t)));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class DocumentSnapshot$1 {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n /** @hideconstructor protected */\n constructor(e, t, n, r, i) {\n this._firestore = e, this._userDataWriter = t, this._key = n, this._document = r, \n this._converter = i;\n }\n /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */ get ref() {\n return new DocumentReference(this._firestore, this._converter, this._key);\n }\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */ exists() {\n return null !== this._document;\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */ data() {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const e = new QueryDocumentSnapshot$1(this._firestore, this._userDataWriter, this._key, this._document, \n /* converter= */ null);\n return this._converter.fromFirestore(e);\n }\n return this._userDataWriter.convertValue(this._document.data.value);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(e) {\n if (this._document) {\n const t = this._document.data.field(__PRIVATE_fieldPathFromArgument(\"DocumentSnapshot.get\", e));\n if (null !== t) return this._userDataWriter.convertValue(t);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data() {\n return super.data();\n }\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */ function __PRIVATE_fieldPathFromArgument(e, t) {\n return \"string\" == typeof t ? __PRIVATE_fieldPathFromDotSeparatedString(e, t) : t instanceof FieldPath ? t._internalPath : t._delegate._internalPath;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e) {\n if (\"L\" /* LimitType.Last */ === e.limitType && 0 === e.explicitOrderBy.length) throw new FirestoreError(D.UNIMPLEMENTED, \"limitToLast() queries require specifying at least one orderBy() clause\");\n}\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */ class AppliableConstraint {}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */ class QueryConstraint extends AppliableConstraint {}\n\nfunction query(e, t, ...n) {\n let r = [];\n t instanceof AppliableConstraint && r.push(t), r = r.concat(n), function __PRIVATE_validateQueryConstraintArray(e) {\n const t = e.filter((e => e instanceof QueryCompositeFilterConstraint)).length, n = e.filter((e => e instanceof QueryFieldFilterConstraint)).length;\n if (t > 1 || t > 0 && n > 0) throw new FirestoreError(D.INVALID_ARGUMENT, \"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.\");\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */ (r);\n for (const t of r) e = t._apply(e);\n return e;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */ class QueryFieldFilterConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(e, t, n) {\n super(), this._field = e, this._op = t, this._value = n, \n /** The type of this query constraint */\n this.type = \"where\";\n }\n static _create(e, t, n) {\n return new QueryFieldFilterConstraint(e, t, n);\n }\n _apply(e) {\n const t = this._parse(e);\n return __PRIVATE_validateNewFieldFilter(e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t));\n }\n _parse(e) {\n const t = __PRIVATE_newUserDataReader(e.firestore), n = function __PRIVATE_newQueryFilter(e, t, n, r, i, s, o) {\n let _;\n if (i.isKeyField()) {\n if (\"array-contains\" /* Operator.ARRAY_CONTAINS */ === s || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid Query. You can't perform '${s}' queries on documentId().`);\n if (\"in\" /* Operator.IN */ === s || \"not-in\" /* Operator.NOT_IN */ === s) {\n __PRIVATE_validateDisjunctiveFilterElements(o, s);\n const t = [];\n for (const n of o) t.push(__PRIVATE_parseDocumentIdValue(r, e, n));\n _ = {\n arrayValue: {\n values: t\n }\n };\n } else _ = __PRIVATE_parseDocumentIdValue(r, e, o);\n } else \"in\" /* Operator.IN */ !== s && \"not-in\" /* Operator.NOT_IN */ !== s && \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), \n _ = __PRIVATE_parseQueryValue(n, t, o, \n /* allowArrays= */ \"in\" /* Operator.IN */ === s || \"not-in\" /* Operator.NOT_IN */ === s);\n return FieldFilter.create(i, s, _);\n }(e._query, \"where\", t, e.firestore._databaseId, this._field, this._op, this._value);\n return n;\n }\n}\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */ function where(e, t, n) {\n const r = t, i = __PRIVATE_fieldPathFromArgument(\"where\", e);\n return QueryFieldFilterConstraint._create(i, r, n);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */ class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n e, t) {\n super(), this.type = e, this._queryConstraints = t;\n }\n static _create(e, t) {\n return new QueryCompositeFilterConstraint(e, t);\n }\n _parse(e) {\n const t = this._queryConstraints.map((t => t._parse(e))).filter((e => e.getFilters().length > 0));\n return 1 === t.length ? t[0] : CompositeFilter.create(t, this._getOperator());\n }\n _apply(e) {\n const t = this._parse(e);\n return 0 === t.getFilters().length ? e : (function __PRIVATE_validateNewFilter(e, t) {\n let n = e;\n const r = t.getFlattenedFilters();\n for (const e of r) __PRIVATE_validateNewFieldFilter(n, e), n = __PRIVATE_queryWithAddedFilter(n, e);\n }\n // Checks if any of the provided filter operators are included in the given list of filters and\n // returns the first one that is, or null if none are.\n (e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t)));\n }\n _getQueryConstraints() {\n return this._queryConstraints;\n }\n _getOperator() {\n return \"and\" === this.type ? \"and\" /* CompositeOperator.AND */ : \"or\" /* CompositeOperator.OR */;\n }\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */ function or(...e) {\n // Only support QueryFilterConstraints\n return e.forEach((e => __PRIVATE_validateQueryFilterConstraint(\"or\", e))), QueryCompositeFilterConstraint._create(\"or\" /* CompositeOperator.OR */ , e);\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */ function and(...e) {\n // Only support QueryFilterConstraints\n return e.forEach((e => __PRIVATE_validateQueryFilterConstraint(\"and\", e))), QueryCompositeFilterConstraint._create(\"and\" /* CompositeOperator.AND */ , e);\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */ class QueryOrderByConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(e, t) {\n super(), this._field = e, this._direction = t, \n /** The type of this query constraint */\n this.type = \"orderBy\";\n }\n static _create(e, t) {\n return new QueryOrderByConstraint(e, t);\n }\n _apply(e) {\n const t = function __PRIVATE_newQueryOrderBy(e, t, n) {\n if (null !== e.startAt) throw new FirestoreError(D.INVALID_ARGUMENT, \"Invalid query. You must not call startAt() or startAfter() before calling orderBy().\");\n if (null !== e.endAt) throw new FirestoreError(D.INVALID_ARGUMENT, \"Invalid query. You must not call endAt() or endBefore() before calling orderBy().\");\n return new OrderBy(t, n);\n }\n /**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */ (e._query, this._field, this._direction);\n return new Query(e.firestore, e.converter, function __PRIVATE_queryWithAddedOrderBy(e, t) {\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const n = e.explicitOrderBy.concat([ t ]);\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, n, e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);\n }(e._query, t));\n }\n}\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */ function orderBy(e, t = \"asc\") {\n const n = t, r = __PRIVATE_fieldPathFromArgument(\"orderBy\", e);\n return QueryOrderByConstraint._create(r, n);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */ class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n e, t, n) {\n super(), this.type = e, this._limit = t, this._limitType = n;\n }\n static _create(e, t, n) {\n return new QueryLimitConstraint(e, t, n);\n }\n _apply(e) {\n return new Query(e.firestore, e.converter, __PRIVATE_queryWithLimit(e._query, this._limit, this._limitType));\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function limit(e) {\n return __PRIVATE_validatePositiveNumber(\"limit\", e), QueryLimitConstraint._create(\"limit\", e, \"F\" /* LimitType.First */);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function limitToLast(e) {\n return __PRIVATE_validatePositiveNumber(\"limitToLast\", e), QueryLimitConstraint._create(\"limitToLast\", e, \"L\" /* LimitType.Last */);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */ class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n e, t, n) {\n super(), this.type = e, this._docOrFields = t, this._inclusive = n;\n }\n static _create(e, t, n) {\n return new QueryStartAtConstraint(e, t, n);\n }\n _apply(e) {\n const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive);\n return new Query(e.firestore, e.converter, function __PRIVATE_queryWithStartAt(e, t) {\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, t, e.endAt);\n }(e._query, t));\n }\n}\n\nfunction startAt(...e) {\n return QueryStartAtConstraint._create(\"startAt\", e, \n /*inclusive=*/ !0);\n}\n\nfunction startAfter(...e) {\n return QueryStartAtConstraint._create(\"startAfter\", e, \n /*inclusive=*/ !1);\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */ class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n e, t, n) {\n super(), this.type = e, this._docOrFields = t, this._inclusive = n;\n }\n static _create(e, t, n) {\n return new QueryEndAtConstraint(e, t, n);\n }\n _apply(e) {\n const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive);\n return new Query(e.firestore, e.converter, function __PRIVATE_queryWithEndAt(e, t) {\n return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, t);\n }(e._query, t));\n }\n}\n\nfunction endBefore(...e) {\n return QueryEndAtConstraint._create(\"endBefore\", e, \n /*inclusive=*/ !1);\n}\n\nfunction endAt(...e) {\n return QueryEndAtConstraint._create(\"endAt\", e, \n /*inclusive=*/ !0);\n}\n\n/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(e, t, n, r) {\n if (n[0] = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(n[0]), n[0] instanceof DocumentSnapshot$1) return function __PRIVATE_newQueryBoundFromDocument(e, t, n, r, i) {\n if (!r) throw new FirestoreError(D.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);\n const s = [];\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const n of __PRIVATE_queryNormalizedOrderBy(e)) if (n.field.isKeyField()) s.push(__PRIVATE_refValue(t, r.key)); else {\n const e = r.data.field(n.field);\n if (__PRIVATE_isServerTimestamp(e)) throw new FirestoreError(D.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field \"' + n.field + '\" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');\n if (null === e) {\n const e = n.field.canonicalString();\n throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`);\n }\n s.push(e);\n }\n return new Bound(s, i);\n }\n /**\n * Converts a list of field values to a `Bound` for the given query.\n */ (e._query, e.firestore._databaseId, t, n[0]._document, r);\n {\n const i = __PRIVATE_newUserDataReader(e.firestore);\n return function __PRIVATE_newQueryBoundFromFields(e, t, n, r, i, s) {\n // Use explicit order by's because it has to match the query the user made\n const o = e.explicitOrderBy;\n if (i.length > o.length) throw new FirestoreError(D.INVALID_ARGUMENT, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);\n const _ = [];\n for (let s = 0; s < i.length; s++) {\n const a = i[s];\n if (o[s].field.isKeyField()) {\n if (\"string\" != typeof a) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof a}`);\n if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== a.indexOf(\"/\")) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${a}' contains a slash.`);\n const n = e.path.child(ResourcePath.fromString(a));\n if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);\n const i = new DocumentKey(n);\n _.push(__PRIVATE_refValue(t, i));\n } else {\n const e = __PRIVATE_parseQueryValue(n, r, a);\n _.push(e);\n }\n }\n return new Bound(_, s);\n }\n /**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */ (e._query, e.firestore._databaseId, i, t, n, r);\n }\n}\n\nfunction __PRIVATE_parseDocumentIdValue(e, t, n) {\n if (\"string\" == typeof (n = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(n))) {\n if (\"\" === n) throw new FirestoreError(D.INVALID_ARGUMENT, \"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.\");\n if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== n.indexOf(\"/\")) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);\n const r = t.path.child(ResourcePath.fromString(n));\n if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);\n return __PRIVATE_refValue(e, new DocumentKey(r));\n }\n if (n instanceof DocumentReference) return __PRIVATE_refValue(e, n._key);\n throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(n)}.`);\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */ function __PRIVATE_validateDisjunctiveFilterElements(e, t) {\n if (!Array.isArray(e) || 0 === e.length) throw new FirestoreError(D.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */ function __PRIVATE_validateNewFieldFilter(e, t) {\n const n = function __PRIVATE_findOpInsideFilters(e, t) {\n for (const n of e) for (const e of n.getFlattenedFilters()) if (t.indexOf(e.op) >= 0) return e.op;\n return null;\n }(e.filters, function __PRIVATE_conflictingOps(e) {\n switch (e) {\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return [ \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n case \"in\" /* Operator.IN */ :\n return [ \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"not-in\" /* Operator.NOT_IN */ :\n return [ \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ , \"!=\" /* Operator.NOT_EQUAL */ ];\n\n default:\n return [];\n }\n }(t.op));\n if (null !== n) \n // Special case when it's a duplicate op to give a slightly clearer error message.\n throw n === t.op ? new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${t.op.toString()}' filter.`) : new FirestoreError(D.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`);\n}\n\nfunction __PRIVATE_validateQueryFilterConstraint(e, t) {\n if (!(t instanceof QueryFieldFilterConstraint || t instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(D.INVALID_ARGUMENT, `Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);\n}\n\nclass AbstractUserDataWriter {\n convertValue(e, t = \"none\") {\n switch (__PRIVATE_typeOrder(e)) {\n case 0 /* TypeOrder.NullValue */ :\n return null;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return e.booleanValue;\n\n case 2 /* TypeOrder.NumberValue */ :\n return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return this.convertTimestamp(e.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return this.convertServerTimestamp(e, t);\n\n case 5 /* TypeOrder.StringValue */ :\n return e.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));\n\n case 7 /* TypeOrder.RefValue */ :\n return this.convertReference(e.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return this.convertGeoPoint(e.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return this.convertArray(e.arrayValue, t);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return this.convertObject(e.mapValue, t);\n\n default:\n throw fail();\n }\n }\n convertObject(e, t) {\n return this.convertObjectMap(e.fields, t);\n }\n /**\n * @internal\n */ convertObjectMap(e, t = \"none\") {\n const n = {};\n return forEach(e, ((e, r) => {\n n[e] = this.convertValue(r, t);\n })), n;\n }\n convertGeoPoint(e) {\n return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(e.longitude));\n }\n convertArray(e, t) {\n return (e.values || []).map((e => this.convertValue(e, t)));\n }\n convertServerTimestamp(e, t) {\n switch (t) {\n case \"previous\":\n const n = __PRIVATE_getPreviousValue(e);\n return null == n ? null : this.convertValue(n, t);\n\n case \"estimate\":\n return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));\n\n default:\n return null;\n }\n }\n convertTimestamp(e) {\n const t = __PRIVATE_normalizeTimestamp(e);\n return new Timestamp(t.seconds, t.nanos);\n }\n convertDocumentKey(e, t) {\n const n = ResourcePath.fromString(e);\n __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n));\n const r = new DatabaseId(n.get(1), n.get(3)), i = new DocumentKey(n.popFirst(5));\n return r.isEqual(t) || \n // TODO(b/64130202): Somehow support foreign references.\n __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`), \n i;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */ function __PRIVATE_applyFirestoreDataConverter(e, t, n) {\n let r;\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return r = e ? n && (n.merge || n.mergeFields) ? e.toFirestore(t, n) : e.toFirestore(t) : t, \n r;\n}\n\nclass __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(e) {\n super(), this.firestore = e;\n }\n convertBytes(e) {\n return new Bytes(e);\n }\n convertReference(e) {\n const t = this.convertDocumentKey(e, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, t);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */ function sum(e) {\n return new AggregateField(\"sum\", __PRIVATE_fieldPathFromArgument$1(\"sum\", e));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */ function average(e) {\n return new AggregateField(\"avg\", __PRIVATE_fieldPathFromArgument$1(\"average\", e));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */ function count() {\n return new AggregateField(\"count\");\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */ function aggregateFieldEqual(e, t) {\n var n, r;\n return e instanceof AggregateField && t instanceof AggregateField && e.aggregateType === t.aggregateType && (null === (n = e._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (r = t._internalFieldPath) || void 0 === r ? void 0 : r.canonicalString());\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */ function aggregateQuerySnapshotEqual(e, t) {\n return queryEqual(e.query, t.query) && (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.deepEqual)(e.data(), t.data());\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */ class SnapshotMetadata {\n /** @hideconstructor */\n constructor(e, t) {\n this.hasPendingWrites = e, this.fromCache = t;\n }\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */ isEqual(e) {\n return this.hasPendingWrites === e.hasPendingWrites && this.fromCache === e.fromCache;\n }\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class DocumentSnapshot extends DocumentSnapshot$1 {\n /** @hideconstructor protected */\n constructor(e, t, n, r, i, s) {\n super(e, t, n, r, s), this._firestore = e, this._firestoreImpl = e, this.metadata = i;\n }\n /**\n * Returns whether or not the data exists. True if the document exists.\n */ exists() {\n return super.exists();\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */ data(e = {}) {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, \n /* converter= */ null);\n return this._converter.fromFirestore(t, e);\n }\n return this._userDataWriter.convertValue(this._document.data.value, e.serverTimestamps);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(e, t = {}) {\n if (this._document) {\n const n = this._document.data.field(__PRIVATE_fieldPathFromArgument(\"DocumentSnapshot.get\", e));\n if (null !== n) return this._userDataWriter.convertValue(n, t.serverTimestamps);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class QueryDocumentSnapshot extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(e = {}) {\n return super.data(e);\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */ class QuerySnapshot {\n /** @hideconstructor */\n constructor(e, t, n, r) {\n this._firestore = e, this._userDataWriter = t, this._snapshot = r, this.metadata = new SnapshotMetadata(r.hasPendingWrites, r.fromCache), \n this.query = n;\n }\n /** An array of all the documents in the `QuerySnapshot`. */ get docs() {\n const e = [];\n return this.forEach((t => e.push(t))), e;\n }\n /** The number of documents in the `QuerySnapshot`. */ get size() {\n return this._snapshot.docs.size;\n }\n /** True if there are no documents in the `QuerySnapshot`. */ get empty() {\n return 0 === this.size;\n }\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */ forEach(e, t) {\n this._snapshot.docs.forEach((n => {\n e.call(t, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, n.key, n, new SnapshotMetadata(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));\n }));\n }\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */ docChanges(e = {}) {\n const t = !!e.includeMetadataChanges;\n if (t && this._snapshot.excludesMetadataChanges) throw new FirestoreError(D.INVALID_ARGUMENT, \"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().\");\n return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === t || (this._cachedChanges = \n /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\n function __PRIVATE_changesFromSnapshot(e, t) {\n if (e._snapshot.oldDocs.isEmpty()) {\n let t = 0;\n return e._snapshot.docChanges.map((n => {\n const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, n.doc.key, n.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(n.doc.key), e._snapshot.fromCache), e.query.converter);\n return n.doc, {\n type: \"added\",\n doc: r,\n oldIndex: -1,\n newIndex: t++\n };\n }));\n }\n {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let n = e._snapshot.oldDocs;\n return e._snapshot.docChanges.filter((e => t || 3 /* ChangeType.Metadata */ !== e.type)).map((t => {\n const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, t.doc.key, t.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(t.doc.key), e._snapshot.fromCache), e.query.converter);\n let i = -1, s = -1;\n return 0 /* ChangeType.Added */ !== t.type && (i = n.indexOf(t.doc.key), n = n.delete(t.doc.key)), \n 1 /* ChangeType.Removed */ !== t.type && (n = n.add(t.doc), s = n.indexOf(t.doc.key)), \n {\n type: __PRIVATE_resultChangeType(t.type),\n doc: r,\n oldIndex: i,\n newIndex: s\n };\n }));\n }\n }(this, t), this._cachedChangesIncludeMetadataChanges = t), this._cachedChanges;\n }\n}\n\nfunction __PRIVATE_resultChangeType(e) {\n switch (e) {\n case 0 /* ChangeType.Added */ :\n return \"added\";\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n return \"modified\";\n\n case 1 /* ChangeType.Removed */ :\n return \"removed\";\n\n default:\n return fail();\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */ function snapshotEqual(e, t) {\n return e instanceof DocumentSnapshot && t instanceof DocumentSnapshot ? e._firestore === t._firestore && e._key.isEqual(t._key) && (null === e._document ? null === t._document : e._document.isEqual(t._document)) && e._converter === t._converter : e instanceof QuerySnapshot && t instanceof QuerySnapshot && (e._firestore === t._firestore && queryEqual(e.query, t.query) && e.metadata.isEqual(t.metadata) && e._snapshot.isEqual(t._snapshot));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDoc(e) {\n e = __PRIVATE_cast(e, DocumentReference);\n const t = __PRIVATE_cast(e.firestore, Firestore);\n return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key).then((n => __PRIVATE_convertToDocSnapshot(t, e, n)));\n}\n\nclass __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter {\n constructor(e) {\n super(), this.firestore = e;\n }\n convertBytes(e) {\n return new Bytes(e);\n }\n convertReference(e) {\n const t = this.convertDocumentKey(e, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, t);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDocFromCache(e) {\n e = __PRIVATE_cast(e, DocumentReference);\n const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n return __PRIVATE_firestoreClientGetDocumentFromLocalCache(n, e._key).then((n => new DocumentSnapshot(t, r, e._key, n, new SnapshotMetadata(null !== n && n.hasLocalMutations, \n /* fromCache= */ !0), e.converter)));\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDocFromServer(e) {\n e = __PRIVATE_cast(e, DocumentReference);\n const t = __PRIVATE_cast(e.firestore, Firestore);\n return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key, {\n source: \"server\"\n }).then((n => __PRIVATE_convertToDocSnapshot(t, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocs(e) {\n e = __PRIVATE_cast(e, Query);\n const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query), __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocsFromCache(e) {\n e = __PRIVATE_cast(e, Query);\n const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n return __PRIVATE_firestoreClientGetDocumentsFromLocalCache(n, e._query).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocsFromServer(e) {\n e = __PRIVATE_cast(e, Query);\n const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query, {\n source: \"server\"\n }).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\nfunction setDoc(e, t, n) {\n e = __PRIVATE_cast(e, DocumentReference);\n const r = __PRIVATE_cast(e.firestore, Firestore), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t, n);\n return executeWrite(r, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(r), \"setDoc\", e._key, i, null !== e.converter, n).toMutation(e._key, Precondition.none()) ]);\n}\n\nfunction updateDoc(e, t, n, ...r) {\n e = __PRIVATE_cast(e, DocumentReference);\n const i = __PRIVATE_cast(e.firestore, Firestore), s = __PRIVATE_newUserDataReader(i);\n let o;\n o = \"string\" == typeof (\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n t = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(s, \"updateDoc\", e._key, t, n, r) : __PRIVATE_parseUpdateData(s, \"updateDoc\", e._key, t);\n return executeWrite(i, [ o.toMutation(e._key, Precondition.exists(!0)) ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */ function deleteDoc(e) {\n return executeWrite(__PRIVATE_cast(e.firestore, Firestore), [ new __PRIVATE_DeleteMutation(e._key, Precondition.none()) ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */ function addDoc(e, t) {\n const n = __PRIVATE_cast(e.firestore, Firestore), r = doc(e), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t);\n return executeWrite(n, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore), \"addDoc\", r._key, i, null !== e.converter, {}).toMutation(r._key, Precondition.exists(!1)) ]).then((() => r));\n}\n\nfunction onSnapshot(e, ...t) {\n var n, r, i;\n e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(e);\n let s = {\n includeMetadataChanges: !1,\n source: \"default\"\n }, o = 0;\n \"object\" != typeof t[o] || __PRIVATE_isPartialObserver(t[o]) || (s = t[o], o++);\n const _ = {\n includeMetadataChanges: s.includeMetadataChanges,\n source: s.source\n };\n if (__PRIVATE_isPartialObserver(t[o])) {\n const e = t[o];\n t[o] = null === (n = e.next) || void 0 === n ? void 0 : n.bind(e), t[o + 1] = null === (r = e.error) || void 0 === r ? void 0 : r.bind(e), \n t[o + 2] = null === (i = e.complete) || void 0 === i ? void 0 : i.bind(e);\n }\n let a, u, c;\n if (e instanceof DocumentReference) u = __PRIVATE_cast(e.firestore, Firestore), \n c = __PRIVATE_newQueryForPath(e._key.path), a = {\n next: n => {\n t[o] && t[o](__PRIVATE_convertToDocSnapshot(u, e, n));\n },\n error: t[o + 1],\n complete: t[o + 2]\n }; else {\n const n = __PRIVATE_cast(e, Query);\n u = __PRIVATE_cast(n.firestore, Firestore), c = n._query;\n const r = new __PRIVATE_ExpUserDataWriter(u);\n a = {\n next: e => {\n t[o] && t[o](new QuerySnapshot(u, r, n, e));\n },\n error: t[o + 1],\n complete: t[o + 2]\n }, __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query);\n }\n return function __PRIVATE_firestoreClientListen(e, t, n, r) {\n const i = new __PRIVATE_AsyncObserver(r), s = new __PRIVATE_QueryListener(t, i, n);\n return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e), s))), \n () => {\n i.Qa(), e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e), s)));\n };\n }(ensureFirestoreConfigured(u), c, _, a);\n}\n\nfunction onSnapshotsInSync(e, t) {\n return __PRIVATE_firestoreClientAddSnapshotsInSyncListener(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), __PRIVATE_isPartialObserver(t) ? t : {\n next: t\n });\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */ function executeWrite(e, t) {\n return function __PRIVATE_firestoreClientWrite(e, t) {\n const n = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e), t, n))), \n n.promise;\n }(ensureFirestoreConfigured(e), t);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */ function __PRIVATE_convertToDocSnapshot(e, t, n) {\n const r = n.docs.get(t._key), i = new __PRIVATE_ExpUserDataWriter(e);\n return new DocumentSnapshot(e, i, t._key, r, new SnapshotMetadata(n.hasPendingWrites, n.fromCache), t.converter);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */ function getCountFromServer(e) {\n return getAggregateFromServer(e, {\n count: count()\n });\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */ function getAggregateFromServer(e, t) {\n const n = __PRIVATE_cast(e.firestore, Firestore), r = ensureFirestoreConfigured(n), i = function __PRIVATE_mapToArray(e, t) {\n const n = [];\n for (const r in e) Object.prototype.hasOwnProperty.call(e, r) && n.push(t(e[r], r, e));\n return n;\n }(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath)));\n // Run the aggregation and convert the results\n return function __PRIVATE_firestoreClientRunAggregateQuery(e, t, n) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => {\n // Implement and call executeAggregateQueryViaSnapshotListener, similar\n // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n // above\n try {\n // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n const i = await __PRIVATE_getDatastore(e);\n r.resolve(__PRIVATE_invokeRunAggregationQueryRpc(i, t, n));\n } catch (e) {\n r.reject(e);\n }\n })), r.promise;\n }(r, e._query, i).then((t => \n /**\n * Converts the core aggregration result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\n function __PRIVATE_convertToAggregateQuerySnapshot(e, t, n) {\n const r = new __PRIVATE_ExpUserDataWriter(e);\n return new AggregateQuerySnapshot(t, r, n);\n }\n /**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n, e, t)));\n}\n\nclass __PRIVATE_MemoryLocalCacheImpl {\n constructor(e) {\n this.kind = \"memory\", this._onlineComponentProvider = new OnlineComponentProvider, \n (null == e ? void 0 : e.garbageCollector) ? this._offlineComponentProvider = e.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = new MemoryOfflineComponentProvider;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass __PRIVATE_PersistentLocalCacheImpl {\n constructor(e) {\n let t;\n this.kind = \"persistent\", (null == e ? void 0 : e.tabManager) ? (e.tabManager._initialize(e), \n t = e.tabManager) : (t = persistentSingleTabManager(void 0), t._initialize(e)), \n this._onlineComponentProvider = t._onlineComponentProvider, this._offlineComponentProvider = t._offlineComponentProvider;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass __PRIVATE_MemoryEagerGabageCollectorImpl {\n constructor() {\n this.kind = \"memoryEager\", this._offlineComponentProvider = new MemoryOfflineComponentProvider;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass __PRIVATE_MemoryLruGabageCollectorImpl {\n constructor(e) {\n this.kind = \"memoryLru\", this._offlineComponentProvider = new __PRIVATE_LruGcMemoryOfflineComponentProvider(e);\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */ function memoryEagerGarbageCollector() {\n return new __PRIVATE_MemoryEagerGabageCollectorImpl;\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */ function memoryLruGarbageCollector(e) {\n return new __PRIVATE_MemoryLruGabageCollectorImpl(null == e ? void 0 : e.cacheSizeBytes);\n}\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */ function memoryLocalCache(e) {\n return new __PRIVATE_MemoryLocalCacheImpl(e);\n}\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */ function persistentLocalCache(e) {\n return new __PRIVATE_PersistentLocalCacheImpl(e);\n}\n\nclass __PRIVATE_SingleTabManagerImpl {\n constructor(e) {\n this.forceOwnership = e, this.kind = \"persistentSingleTab\";\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n /**\n * @internal\n */ _initialize(e) {\n this._onlineComponentProvider = new OnlineComponentProvider, this._offlineComponentProvider = new __PRIVATE_IndexedDbOfflineComponentProvider(this._onlineComponentProvider, null == e ? void 0 : e.cacheSizeBytes, this.forceOwnership);\n }\n}\n\nclass __PRIVATE_MultiTabManagerImpl {\n constructor() {\n this.kind = \"PersistentMultipleTab\";\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n /**\n * @internal\n */ _initialize(e) {\n this._onlineComponentProvider = new OnlineComponentProvider, this._offlineComponentProvider = new __PRIVATE_MultiTabOfflineComponentProvider(this._onlineComponentProvider, null == e ? void 0 : e.cacheSizeBytes);\n }\n}\n\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */ function persistentSingleTabManager(e) {\n return new __PRIVATE_SingleTabManagerImpl(null == e ? void 0 : e.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */ function persistentMultipleTabManager() {\n return new __PRIVATE_MultiTabManagerImpl;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Se = {\n maxAttempts: 5\n};\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nclass WriteBatch {\n /** @hideconstructor */\n constructor(e, t) {\n this._firestore = e, this._commitHandler = t, this._mutations = [], this._committed = !1, \n this._dataReader = __PRIVATE_newUserDataReader(e);\n }\n set(e, t, n) {\n this._verifyNotCommitted();\n const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, \"WriteBatch.set\", r._key, i, null !== r.converter, n);\n return this._mutations.push(s.toMutation(r._key, Precondition.none())), this;\n }\n update(e, t, n, ...r) {\n this._verifyNotCommitted();\n const i = __PRIVATE_validateReference(e, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let s;\n return s = \"string\" == typeof (t = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, \"WriteBatch.update\", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, \"WriteBatch.update\", i._key, t), \n this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */ delete(e) {\n this._verifyNotCommitted();\n const t = __PRIVATE_validateReference(e, this._firestore);\n return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(t._key, Precondition.none())), \n this;\n }\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */ commit() {\n return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();\n }\n _verifyNotCommitted() {\n if (this._committed) throw new FirestoreError(D.FAILED_PRECONDITION, \"A write batch can no longer be used after commit() has been called.\");\n }\n}\n\nfunction __PRIVATE_validateReference(e, t) {\n if ((e = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(e)).firestore !== t) throw new FirestoreError(D.INVALID_ARGUMENT, \"Provided document reference is from a different Firestore instance.\");\n return e;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nclass Transaction extends class Transaction$1 {\n /** @hideconstructor */\n constructor(e, t) {\n this._firestore = e, this._transaction = t, this._dataReader = __PRIVATE_newUserDataReader(e);\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(e) {\n const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ t._key ]).then((e => {\n if (!e || 1 !== e.length) return fail();\n const r = e[0];\n if (r.isFoundDocument()) return new DocumentSnapshot$1(this._firestore, n, r.key, r, t.converter);\n if (r.isNoDocument()) return new DocumentSnapshot$1(this._firestore, n, t._key, null, t.converter);\n throw fail();\n }));\n }\n set(e, t, n) {\n const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, \"Transaction.set\", r._key, i, null !== r.converter, n);\n return this._transaction.set(r._key, s), this;\n }\n update(e, t, n, ...r) {\n const i = __PRIVATE_validateReference(e, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let s;\n return s = \"string\" == typeof (t = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.getModularInstance)(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, \"Transaction.update\", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, \"Transaction.update\", i._key, t), \n this._transaction.update(i._key, s), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */ delete(e) {\n const t = __PRIVATE_validateReference(e, this._firestore);\n return this._transaction.delete(t._key), this;\n }\n} {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n /** @hideconstructor */\n constructor(e, t) {\n super(e, t), this._firestore = e;\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(e) {\n const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_ExpUserDataWriter(this._firestore);\n return super.get(e).then((e => new DocumentSnapshot(this._firestore, n, t._key, e._document, new SnapshotMetadata(\n /* hasPendingWrites= */ !1, \n /* fromCache= */ !1), t.converter)));\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */ function runTransaction(e, t, n) {\n e = __PRIVATE_cast(e, Firestore);\n const r = Object.assign(Object.assign({}, Se), n);\n !function __PRIVATE_validateTransactionOptions(e) {\n if (e.maxAttempts < 1) throw new FirestoreError(D.INVALID_ARGUMENT, \"Max attempts must be at least 1\");\n }(r);\n return function __PRIVATE_firestoreClientTransaction(e, t, n) {\n const r = new __PRIVATE_Deferred;\n return e.asyncQueue.enqueueAndForget((async () => {\n const i = await __PRIVATE_getDatastore(e);\n new __PRIVATE_TransactionRunner(e.asyncQueue, i, n, t, r).Ya();\n })), r.promise;\n }(ensureFirestoreConfigured(e), (n => t(new Transaction(e, n))), r);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */ function deleteField() {\n return new __PRIVATE_DeleteFieldValueImpl(\"deleteField\");\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */ function serverTimestamp() {\n return new __PRIVATE_ServerTimestampFieldValueImpl(\"serverTimestamp\");\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */ function arrayUnion(...e) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new __PRIVATE_ArrayUnionFieldValueImpl(\"arrayUnion\", e);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function arrayRemove(...e) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new __PRIVATE_ArrayRemoveFieldValueImpl(\"arrayRemove\", e);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function increment(e) {\n return new __PRIVATE_NumericIncrementFieldValueImpl(\"increment\", e);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */ function writeBatch(e) {\n return ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), new WriteBatch(e, (t => executeWrite(e, t)));\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function setIndexConfiguration(e, t) {\n var n;\n const r = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore));\n if (!r._uninitializedComponentsProvider || \"memory\" === (null === (n = r._uninitializedComponentsProvider) || void 0 === n ? void 0 : n._offlineKind)) \n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n return __PRIVATE_logWarn(\"Cannot enable indexes when persistence is disabled\"), \n Promise.resolve();\n const i = function __PRIVATE_parseIndexes(e) {\n const t = \"string\" == typeof e ? function __PRIVATE_tryParseJson(e) {\n try {\n return JSON.parse(e);\n } catch (e) {\n throw new FirestoreError(D.INVALID_ARGUMENT, \"Failed to parse JSON: \" + (null == e ? void 0 : e.message));\n }\n }(e) : e, n = [];\n if (Array.isArray(t.indexes)) for (const e of t.indexes) {\n const t = __PRIVATE_tryGetString(e, \"collectionGroup\"), r = [];\n if (Array.isArray(e.fields)) for (const t of e.fields) {\n const e = __PRIVATE_fieldPathFromDotSeparatedString(\"setIndexConfiguration\", __PRIVATE_tryGetString(t, \"fieldPath\"));\n \"CONTAINS\" === t.arrayConfig ? r.push(new IndexSegment(e, 2 /* IndexKind.CONTAINS */)) : \"ASCENDING\" === t.order ? r.push(new IndexSegment(e, 0 /* IndexKind.ASCENDING */)) : \"DESCENDING\" === t.order && r.push(new IndexSegment(e, 1 /* IndexKind.DESCENDING */));\n }\n n.push(new FieldIndex(FieldIndex.UNKNOWN_ID, t, r, IndexState.empty()));\n }\n return n;\n }(t);\n return __PRIVATE_firestoreClientSetIndexConfiguration(r, i);\n}\n\nfunction __PRIVATE_tryGetString(e, t) {\n if (\"string\" != typeof e[t]) throw new FirestoreError(D.INVALID_ARGUMENT, \"Missing string value for: \" + t);\n return e[t];\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `PersistentCacheIndexManager` for configuring persistent cache indexes used\n * for local query execution.\n *\n * To use, call `getPersistentCacheIndexManager()` to get an instance.\n */ class PersistentCacheIndexManager {\n /** @hideconstructor */\n constructor(e) {\n this._client = e, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"PersistentCacheIndexManager\";\n }\n}\n\n/**\n * Returns the PersistentCache Index Manager used by the given `Firestore`\n * object.\n *\n * @return The `PersistentCacheIndexManager` instance, or `null` if local\n * persistent storage is not in use.\n */ function getPersistentCacheIndexManager(e) {\n var t;\n e = __PRIVATE_cast(e, Firestore);\n const n = be.get(e);\n if (n) return n;\n const r = ensureFirestoreConfigured(e);\n if (\"persistent\" !== (null === (t = r._uninitializedComponentsProvider) || void 0 === t ? void 0 : t._offlineKind)) return null;\n const i = new PersistentCacheIndexManager(r);\n return be.set(e, i), i;\n}\n\n/**\n * Enables the SDK to create persistent cache indexes automatically for local\n * query execution when the SDK believes cache indexes can help improve\n * performance.\n *\n * This feature is disabled by default.\n */ function enablePersistentCacheIndexAutoCreation(e) {\n __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !0);\n}\n\n/**\n * Stops creating persistent cache indexes automatically for local query\n * execution. The indexes which have been created by calling\n * `enablePersistentCacheIndexAutoCreation()` still take effect.\n */ function disablePersistentCacheIndexAutoCreation(e) {\n __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !1);\n}\n\n/**\n * Removes all persistent cache indexes.\n *\n * Please note this function will also deletes indexes generated by\n * `setIndexConfiguration()`, which is deprecated.\n */ function deleteAllPersistentCacheIndexes(e) {\n e._client.verifyNotTerminated();\n __PRIVATE_firestoreClientDeleteAllFieldIndexes(e._client).then((e => __PRIVATE_logDebug(\"deleting all persistent cache indexes succeeded\"))).catch((e => __PRIVATE_logWarn(\"deleting all persistent cache indexes failed\", e)));\n}\n\nfunction __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, t) {\n e._client.verifyNotTerminated();\n __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e._client, t).then((e => __PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e => __PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${t} failed`, e)));\n}\n\n/**\n * Maps `Firestore` instances to their corresponding\n * `PersistentCacheIndexManager` instances.\n *\n * Use a `WeakMap` so that the mapping will be automatically dropped when the\n * `Firestore` instance is garbage collected. This emulates a private member\n * as described in https://goo.gle/454yvug.\n */ const be = new WeakMap;\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */ class TestingHooks {\n constructor() {\n throw new Error(\"instances of this class should not be created\");\n }\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */ static onExistenceFilterMismatch(e) {\n return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e);\n }\n}\n\n/**\n * The implementation of `TestingHooksSpi`.\n */ class __PRIVATE_TestingHooksSpiImpl {\n constructor() {\n this.Mu = new Map;\n }\n static get instance() {\n return De || (De = new __PRIVATE_TestingHooksSpiImpl, function __PRIVATE_setTestingHooksSpi(e) {\n if (ce) throw new Error(\"a TestingHooksSpi instance is already set\");\n ce = e;\n }(De)), De;\n }\n tt(e) {\n this.Mu.forEach((t => t(e)));\n }\n onExistenceFilterMismatch(e) {\n const t = Symbol(), n = this.Mu;\n return n.set(t, e), () => n.delete(t);\n }\n}\n\nlet De = null;\n\n/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */ !function __PRIVATE_registerFirestore(e, t = !0) {\n !function __PRIVATE_setSDKVersion(e) {\n S = e;\n }(_firebase_app__WEBPACK_IMPORTED_MODULE_0__.SDK_VERSION), (0,_firebase_app__WEBPACK_IMPORTED_MODULE_0__._registerComponent)(new _firebase_component__WEBPACK_IMPORTED_MODULE_1__.Component(\"firestore\", ((e, {instanceIdentifier: n, options: r}) => {\n const i = e.getProvider(\"app\").getImmediate(), s = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e.getProvider(\"auth-internal\")), new __PRIVATE_FirebaseAppCheckTokenProvider(e.getProvider(\"app-check-internal\")), function __PRIVATE_databaseIdFromApp(e, t) {\n if (!Object.prototype.hasOwnProperty.apply(e.options, [ \"projectId\" ])) throw new FirestoreError(D.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n return new DatabaseId(e.options.projectId, t);\n }(i, n), i);\n return r = Object.assign({\n useFetchStreams: t\n }, r), s._setSettings(r), s;\n }), \"PUBLIC\").setMultipleInstances(!0)), (0,_firebase_app__WEBPACK_IMPORTED_MODULE_0__.registerVersion)(w, \"4.5.0\", e), \n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n (0,_firebase_app__WEBPACK_IMPORTED_MODULE_0__.registerVersion)(w, \"4.5.0\", \"esm2017\");\n}();\n\n\n//# sourceMappingURL=index.esm2017.js.map\n\n\n//# sourceURL=webpack://compass/./node_modules/@firebase/firestore/dist/index.esm2017.js?");
+
+/***/ }),
+
+/***/ "./node_modules/@firebase/util/dist/index.esm2017.js":
+/*!***********************************************************!*\
+ !*** ./node_modules/@firebase/util/dist/index.esm2017.js ***!
+ \***********************************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CONSTANTS: () => (/* binding */ CONSTANTS),\n/* harmony export */ DecodeBase64StringError: () => (/* binding */ DecodeBase64StringError),\n/* harmony export */ Deferred: () => (/* binding */ Deferred),\n/* harmony export */ ErrorFactory: () => (/* binding */ ErrorFactory),\n/* harmony export */ FirebaseError: () => (/* binding */ FirebaseError),\n/* harmony export */ MAX_VALUE_MILLIS: () => (/* binding */ MAX_VALUE_MILLIS),\n/* harmony export */ RANDOM_FACTOR: () => (/* binding */ RANDOM_FACTOR),\n/* harmony export */ Sha1: () => (/* binding */ Sha1),\n/* harmony export */ areCookiesEnabled: () => (/* binding */ areCookiesEnabled),\n/* harmony export */ assert: () => (/* binding */ assert),\n/* harmony export */ assertionError: () => (/* binding */ assertionError),\n/* harmony export */ async: () => (/* binding */ async),\n/* harmony export */ base64: () => (/* binding */ base64),\n/* harmony export */ base64Decode: () => (/* binding */ base64Decode),\n/* harmony export */ base64Encode: () => (/* binding */ base64Encode),\n/* harmony export */ base64urlEncodeWithoutPadding: () => (/* binding */ base64urlEncodeWithoutPadding),\n/* harmony export */ calculateBackoffMillis: () => (/* binding */ calculateBackoffMillis),\n/* harmony export */ contains: () => (/* binding */ contains),\n/* harmony export */ createMockUserToken: () => (/* binding */ createMockUserToken),\n/* harmony export */ createSubscribe: () => (/* binding */ createSubscribe),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ deepCopy: () => (/* binding */ deepCopy),\n/* harmony export */ deepEqual: () => (/* binding */ deepEqual),\n/* harmony export */ deepExtend: () => (/* binding */ deepExtend),\n/* harmony export */ errorPrefix: () => (/* binding */ errorPrefix),\n/* harmony export */ extractQuerystring: () => (/* binding */ extractQuerystring),\n/* harmony export */ getDefaultAppConfig: () => (/* binding */ getDefaultAppConfig),\n/* harmony export */ getDefaultEmulatorHost: () => (/* binding */ getDefaultEmulatorHost),\n/* harmony export */ getDefaultEmulatorHostnameAndPort: () => (/* binding */ getDefaultEmulatorHostnameAndPort),\n/* harmony export */ getDefaults: () => (/* binding */ getDefaults),\n/* harmony export */ getExperimentalSetting: () => (/* binding */ getExperimentalSetting),\n/* harmony export */ getGlobal: () => (/* binding */ getGlobal),\n/* harmony export */ getModularInstance: () => (/* binding */ getModularInstance),\n/* harmony export */ getUA: () => (/* binding */ getUA),\n/* harmony export */ isAdmin: () => (/* binding */ isAdmin),\n/* harmony export */ isBrowser: () => (/* binding */ isBrowser),\n/* harmony export */ isBrowserExtension: () => (/* binding */ isBrowserExtension),\n/* harmony export */ isElectron: () => (/* binding */ isElectron),\n/* harmony export */ isEmpty: () => (/* binding */ isEmpty),\n/* harmony export */ isIE: () => (/* binding */ isIE),\n/* harmony export */ isIndexedDBAvailable: () => (/* binding */ isIndexedDBAvailable),\n/* harmony export */ isMobileCordova: () => (/* binding */ isMobileCordova),\n/* harmony export */ isNode: () => (/* binding */ isNode),\n/* harmony export */ isNodeSdk: () => (/* binding */ isNodeSdk),\n/* harmony export */ isReactNative: () => (/* binding */ isReactNative),\n/* harmony export */ isSafari: () => (/* binding */ isSafari),\n/* harmony export */ isUWP: () => (/* binding */ isUWP),\n/* harmony export */ isValidFormat: () => (/* binding */ isValidFormat),\n/* harmony export */ isValidTimestamp: () => (/* binding */ isValidTimestamp),\n/* harmony export */ issuedAtTime: () => (/* binding */ issuedAtTime),\n/* harmony export */ jsonEval: () => (/* binding */ jsonEval),\n/* harmony export */ map: () => (/* binding */ map),\n/* harmony export */ ordinal: () => (/* binding */ ordinal),\n/* harmony export */ promiseWithTimeout: () => (/* binding */ promiseWithTimeout),\n/* harmony export */ querystring: () => (/* binding */ querystring),\n/* harmony export */ querystringDecode: () => (/* binding */ querystringDecode),\n/* harmony export */ safeGet: () => (/* binding */ safeGet),\n/* harmony export */ stringLength: () => (/* binding */ stringLength),\n/* harmony export */ stringToByteArray: () => (/* binding */ stringToByteArray),\n/* harmony export */ stringify: () => (/* binding */ stringify),\n/* harmony export */ uuidv4: () => (/* binding */ uuidv4),\n/* harmony export */ validateArgCount: () => (/* binding */ validateArgCount),\n/* harmony export */ validateCallback: () => (/* binding */ validateCallback),\n/* harmony export */ validateContextObject: () => (/* binding */ validateContextObject),\n/* harmony export */ validateIndexedDBOpenable: () => (/* binding */ validateIndexedDBOpenable),\n/* harmony export */ validateNamespace: () => (/* binding */ validateNamespace)\n/* harmony export */ });\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nconst CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nconst assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nconst assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst stringToByteArray$1 = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n const c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n const c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n const c4 = bytes[pos++];\r\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray(input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n const byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length; i += 3) {\r\n const byte1 = input[i];\r\n const haveByte2 = i + 1 < input.length;\r\n const byte2 = haveByte2 ? input[i + 1] : 0;\r\n const haveByte3 = i + 2 < input.length;\r\n const byte3 = haveByte3 ? input[i + 2] : 0;\r\n const outByte1 = byte1 >> 2;\r\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n let outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray(input, webSafe) {\r\n this.init_();\r\n const charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length;) {\r\n const byte1 = charToByteMap[input.charAt(i++)];\r\n const haveByte2 = i < input.length;\r\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n const haveByte3 = i < input.length;\r\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n const haveByte4 = i < input.length;\r\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw new DecodeBase64StringError();\r\n }\r\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_() {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * An error encountered while decoding base64 string.\r\n */\r\nclass DecodeBase64StringError extends Error {\r\n constructor() {\r\n super(...arguments);\r\n this.name = 'DecodeBase64StringError';\r\n }\r\n}\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n const utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n const dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (const prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n * @public\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof __webpack_require__.g !== 'undefined') {\r\n return __webpack_require__.g;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\r\n * The dots are in parens because certain compilers (Vite?) cannot\r\n * handle seeing that variable in comments.\r\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n return;\r\n }\r\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n if (defaultsJsonString) {\r\n return JSON.parse(defaultsJsonString);\r\n }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n if (typeof document === 'undefined') {\r\n return;\r\n }\r\n let match;\r\n try {\r\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n }\r\n catch (e) {\r\n // Some environments such as Angular Universal SSR have a\r\n // `document` object but error on accessing `document.cookie`.\r\n return;\r\n }\r\n const decoded = match && base64Decode(match[1]);\r\n return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n * @public\r\n */\r\nconst getDefaults = () => {\r\n try {\r\n return (getDefaultsFromGlobal() ||\r\n getDefaultsFromEnvVariable() ||\r\n getDefaultsFromCookie());\r\n }\r\n catch (e) {\r\n /**\r\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n * to any environment case we have not accounted for. Log to\r\n * info instead of swallowing so we can find these unknown cases\r\n * and add paths for them if needed.\r\n */\r\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n return;\r\n }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n const host = getDefaultEmulatorHost(productName);\r\n if (!host) {\r\n return undefined;\r\n }\r\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n }\r\n // eslint-disable-next-line no-restricted-globals\r\n const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n if (host[0] === '[') {\r\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n return [host.substring(1, separatorIndex - 1), port];\r\n }\r\n else {\r\n return [host.substring(0, separatorIndex), port];\r\n }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n constructor() {\r\n this.reject = () => { };\r\n this.resolve = () => { };\r\n this.promise = new Promise((resolve, reject) => {\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n const header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n const project = projectId || 'demo-project';\r\n const iat = token.iat || 0;\r\n const sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n const payload = Object.assign({ \r\n // Set all required fields to decent defaults\r\n iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n const signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected or specified.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n var _a;\r\n const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\r\n if (forceEnvironment === 'node') {\r\n return true;\r\n }\r\n else if (forceEnvironment === 'browser') {\r\n return false;\r\n }\r\n try {\r\n return (Object.prototype.toString.call(__webpack_require__.g.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof self === 'object' && self.self === self;\r\n}\r\nfunction isBrowserExtension() {\r\n const runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n const ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n !!navigator.userAgent &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n try {\r\n return typeof indexedDB === 'object';\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise((resolve, reject) => {\r\n try {\r\n let preExist = true;\r\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n const request = self.indexedDB.open(DB_CHECK_NAME);\r\n request.onsuccess = () => {\r\n request.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n }\r\n resolve(true);\r\n };\r\n request.onupgradeneeded = () => {\r\n preExist = false;\r\n };\r\n request.onerror = () => {\r\n var _a;\r\n reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n * // Typescript string literals for type-safe codes\r\n * type Err =\r\n * 'unknown' |\r\n * 'object-not-found'\r\n * ;\r\n *\r\n * // Closure enum for type-safe error codes\r\n * // at-enum {string}\r\n * var Err = {\r\n * UNKNOWN: 'unknown',\r\n * OBJECT_NOT_FOUND: 'object-not-found',\r\n * }\r\n *\r\n * let errors: Map = {\r\n * 'generic-error': \"Unknown error\",\r\n * 'file-not-found': \"Could not find file: {$file}\",\r\n * };\r\n *\r\n * // Type-safe function - must pass a valid error code as param.\r\n * let error = new ErrorFactory('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n *
Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *
Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\n\n//# sourceMappingURL=index.esm2017.js.map\n\n\n//# sourceURL=webpack://compass/./node_modules/@firebase/util/dist/index.esm2017.js?");
+
+/***/ }),
+
/***/ "./node_modules/aaci-prop/esm/calc.js":
/*!********************************************!*\
!*** ./node_modules/aaci-prop/esm/calc.js ***!
@@ -1090,7 +1112,51 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
-eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\");\n/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var jquery_ui_ui_widgets_draggable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery-ui/ui/widgets/draggable */ \"./node_modules/jquery-ui/ui/widgets/draggable.js\");\n/* harmony import */ var jquery_ui_ui_widgets_draggable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery_ui_ui_widgets_draggable__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var jquery_ui_ui_widgets_resizable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jquery-ui/ui/widgets/resizable */ \"./node_modules/jquery-ui/ui/widgets/resizable.js\");\n/* harmony import */ var jquery_ui_ui_widgets_resizable__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jquery_ui_ui_widgets_resizable__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! decimal.js */ \"./node_modules/decimal.js/decimal.mjs\");\n/* harmony import */ var cytoscape__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! cytoscape */ \"./node_modules/cytoscape/dist/cytoscape.cjs.js\");\n/* harmony import */ var cytoscape__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(cytoscape__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var gkcoi__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! gkcoi */ \"./node_modules/gkcoi/esm/index.js\");\n\r\n\r\n\r\n\r\n\r\n\r\njquery__WEBPACK_IMPORTED_MODULE_0___default()(function() {\r\n /*\r\n s_dataはship.js\r\n e_dataはitem.jsより\r\n idがs_dataは文字列\r\n e_dataは数字であることに注意\r\n \r\n 制空シミュを基準にしたときの本家デッキビルダー差異・注意点\r\n 艦ID'のみ'文字列\r\n 改修値が0のとき、キーがそもそもない\r\n */\r\n //艦隊諸元\r\n let com = {\r\n BB:0, //戦艦\r\n BBV:0, //航空戦艦&改装航空戦艦\r\n CV:0, //正規空母\r\n CVB:0, //装甲空母\r\n CVL:0, //軽空母\r\n CA:0, //重巡\r\n CAV:0, //航巡\r\n CL:0, //軽巡\r\n CLT:0, //雷巡\r\n ATU:0, //練習特務艦 欠番\r\n CT:0, //練習巡洋艦\r\n DD:0, //駆逐艦\r\n DE:0, //海防艦\r\n SS:0, //潜水艦\r\n SSV:0, //潜水空母\r\n AV:0, //水母\r\n AO:0, //補給艦\r\n ASU:0, //特務艦 欠番\r\n LHT:0, //灯台補給船 欠番\r\n CVE:0, //特設護衛空母 欠番\r\n LHA:0, //揚陸艦\r\n LST:0, //戦車揚陸艦 欠番\r\n AS:0, //潜水母艦\r\n AR:0 //工作艦\r\n };\r\n let i_json = null; //インポートしたjsonを格納\r\n //艦隊諸元 分岐演算に使う\r\n let f_length = 0; //構成艦数\r\n let f_ids = null;\r\n let f_names = null; //構成艦艦名\r\n let f2_names = null; //随伴艦隊構成艦名 表示の為だけ\r\n let f2_length = 0;\r\n let speed = null; //速度\r\n let f_search = null; //索敵値\r\n //ドラム缶、大発系、電探搭載艦数\r\n let f_drum = 0;\r\n let f_radar = 0;\r\n let f_craft = 0;\r\n let f_kanko = 0;\r\n /*\r\n 読込モード\r\n 1:第一艦隊\r\n 2:第二艦隊\r\n 3:第三艦隊\r\n 4:第四艦隊\r\n 5:水上打撃部隊\r\n 6:空母機動部隊\r\n 7:輸送護衛部隊\r\n 判定も少しはするけど殆ど自己申告\r\n */\r\n let f_united = null;\r\n \r\n //読込時の計算に使うあれこれ\r\n let c_lengths = [];\r\n let c_ids = [];\r\n let c_names = [];\r\n let c_types = [];\r\n let c_searchs = [];\r\n let c_speeds = [];\r\n let c_drums = [];\r\n let c_radars = [];\r\n let c_crafts = [];\r\n let c_kanko = [];\r\n \r\n /*\r\n 艦隊種別選択したやつ(数値)が入る\r\n 1:第一艦隊\r\n 2:第二艦隊\r\n 3:第三艦隊\r\n 4:第四艦隊\r\n 5:空母機動部隊\r\n 6:水上打撃部隊\r\n 7:輸送護衛部隊\r\n */\r\n let selected_type = null;\r\n \r\n //受け付ける海域\r\n const areas = ['1-1','1-2','1-3','1-4','1-5','1-6','2-1','2-2','2-3','2-4','2-5','3-1','3-2','3-3','3-4','3-5','4-1','4-2','4-3','4-4','4-5','5-1','5-2','5-3','5-4','5-5','6-1','6-2','6-3','6-4','6-5','7-1','7-2','7-3','7-3-1','7-4','7-5','57-7','58-1','58-2','58-3','58-4'];\r\n const op_areas = ['4-5','5-3','5-5','6-3','7-3','7-4','7-5','57-7','58-1','58-2','58-3','58-4'];\r\n \r\n //1がキーの値はPhase\r\n let active = {'4-5':{'A':'D','C':'F','I':'J'},'5-3':{'O':'K'}, '5-5':{'F':'D'}, '6-3':{'A':'B'},'7-3':{'1':'0'},'7-4':{'F':'H'},'7-5':{'F':'G','H':'I','O':'P'},'57-7':{'1':'1','A2':'A3','B2':'B3','C':'A3','J':'K'}, '57-7':{'1':'1','A2':'A3','B':'B1','B2':'B3','C':'A3','J':'K'},'58-1':{'1':'1','A':'D','I':'N1','F':'G'},'58-2':{'1':'1','2':'1','B':'E'},'58-3':{'1':'1','2':'1','M':'P'},'58-4':{'1':'1','2':'1','B':'D'}};\r\n \r\n let area = null; //入力で切り替えるの\r\n let drew_area = null; //表示中の海域\r\n \r\n //オプション表示の為のz-index\r\n let z_value = 10;\r\n \r\n //演算開始の為のフラグ\r\n let a_flag = false;\r\n let f_flag = false;\r\n \r\n let rate = {}; //これにルート情報を詰め込んでいく\r\n let track = []; //最後の軌跡\r\n \r\n let cy = null;\r\n\r\n //海域が入力されたら適正かチェックしてフラグ切替\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('.areas').on('click', function() {\r\n setArea(jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).val());\r\n });\r\n //海域入力で発火 オプション表示したり\r\n function setArea(text) {\r\n console.log(`area : ${text}`);\r\n if(areas.includes(text)) {\r\n a_flag = true;\r\n localStorage.setItem('area', text);\r\n if(op_areas.includes(text)) {\r\n //オプションが必要な海域は入力を表示\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#option-box').css('display','block');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#option-box .options').each(function () {\r\n var child = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this);\r\n if (child.attr(\"id\") === text) {\r\n child.css(\"display\", \"block\");\r\n } else {\r\n // 子要素が存在しない場合はdisplayをnoneに設定\r\n child.css(\"display\", \"none\");\r\n }\r\n });\r\n } else {\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#option-box').css('display','none');\r\n }\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#area-container').click();\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#area-display').text(`海域 : ${text}`);\r\n } else {\r\n a_flag = false;\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#option-box').css('display','none');\r\n }\r\n startSim();\r\n }\r\n //オプションドラッグ\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#draggable-list').draggable({ containment: 'window', scroll: false });\r\n //オプションが変更されたら取得してlocalstorageへ保存\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('.option-value').on('input', function() {\r\n var name = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).attr('name');\r\n var type = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).attr('type');\r\n const namePattern = /^([\\dA-Z]+-[\\dA-Z]+)-([\\dA-Z]+)$/i;\r\n const match = name.match(namePattern);\r\n var key = match[1];\r\n var char = match[2];\r\n let value = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).val();\r\n if(jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).attr('type') === 'radio') {\r\n updateActive(key, char, value);\r\n }\r\n startSim();\r\n });\r\n //デッキビルダー読み込み\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').on('input', function() {\r\n var text = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).val();\r\n try {\r\n i_json = JSON.parse(text);\r\n } catch(e) {\r\n console.log(e);\r\n f_flag = false;\r\n alert('処理中断: 形式不正');\r\n //空欄化\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).val('');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).blur();\r\n return;\r\n }\r\n /*\r\n 処理の流れ\r\n 1.貼り付けられた時点で第四艦隊まで読み込んで計算まで済ます\r\n 2.一艦隊しか情報が無ければそのまま演算開始\r\n 3.key:tに値があればその形式で演算開始\r\n それ以外は艦隊形式の選択を待つ\r\n */\r\n //cシリーズ初期化\r\n inCs();\r\n // 1\r\n let zeroCount = 0;\r\n let tar = null;\r\n for(let i = 1;i < 5;i++) {\r\n let count = countShips(i);\r\n c_lengths.push(count);\r\n if(count === 0) {\r\n zeroCount++;\r\n } else {\r\n tar = i;\r\n }\r\n if(count) {\r\n c_ids.push(getIdsFromFleet(i));\r\n console.log(c_ids);\r\n c_names.push(getShipName(i));\r\n c_types.push(getType(i));\r\n c_searchs.push(calcSeek(i));\r\n c_speeds.push(calcSpeed(i));\r\n countUnits(i);\r\n } else {\r\n //第一・第二艦隊が空で第三艦隊だけあるみたいな場合\r\n //空を入れてやる\r\n c_ids.push([]);\r\n c_names.push([]);\r\n c_types.push([]);\r\n c_searchs.push([]);\r\n c_speeds.push([]);\r\n c_drums.push(0);\r\n c_radars.push(0);\r\n c_crafts.push(0);\r\n c_kanko.push(0);\r\n }\r\n }\r\n console.log(`c_lengths : ${c_lengths}`);\r\n console.log(`c_ids : ${c_ids}`);\r\n console.log(`c_searchs : ${c_searchs}`);\r\n console.log(`c_speeds : ${c_speeds}`);\r\n console.log(`c_drums : ${c_drums}, c_radars : ${c_radars}, c_crafts : ${c_crafts}, c_kanko : ${c_kanko}`);\r\n if(zeroCount === 3) {\r\n // 2.情報の有る艦隊が一つだけの場合はそのまま読み込み\r\n setFleetInfo(tar);\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#type-select').css('display', 'none');\r\n //空欄化\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).val('');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).blur();\r\n return;\r\n } else if(zeroCount === 4) {\r\n alert('処理中断: 艦隊が空かも?');\r\n //空欄化\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).val('');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).blur();\r\n return;\r\n }\r\n // 3\r\n let t = null;\r\n if(i_json['f1']['t']) {\r\n t = Number(i_json['f1']['t']);\r\n switch(t) {\r\n case 1:\r\n selected_type = 5;\r\n break;\r\n case 2:\r\n selected_type = 6;\r\n break;\r\n case 3:\r\n selected_type = 7;\r\n break;\r\n }\r\n }\r\n console.log(`t ${t}`);\r\n let view = '艦隊種別';\r\n console.log(`selected_type : ${selected_type}`);\r\n if(selected_type) {\r\n if(selected_type > 4) {\r\n if(c_lengths[0] && c_lengths[1]) { //第一と第二に少なくとも1艦\r\n switch(selected_type) {\r\n case 5:\r\n view = '空母機動部隊';\r\n break;\r\n case 6:\r\n view = '水上打撃部隊';\r\n break;\r\n case 7:\r\n view = '輸送護衛部隊';\r\n break;\r\n }\r\n } else {\r\n alert('第一艦隊もしくは第二艦隊が空?');\r\n setBackSelect();\r\n }\r\n } else {\r\n switch(selected_type) {\r\n case 1:\r\n view = '第一艦隊';\r\n break;\r\n case 2:\r\n view = '第二艦隊';\r\n break;\r\n case 3:\r\n view = '第三艦隊';\r\n break;\r\n case 4:\r\n view = '第四艦隊';\r\n break; \r\n }\r\n }\r\n setFleetInfo(selected_type);\r\n }\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#type-select').css('display', 'block');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#type-select').text(view);\r\n //空欄化\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).val('');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).blur();\r\n });\r\n //\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#type-select').on('mouseover', function() {\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-option-box').css('display', 'block');\r\n });\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-option-box').on('mouseleave', function() {\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-option-box').css('display', 'none');\r\n });\r\n //艦隊形式が選択されたら該当する計算データを変数反映して演算開始\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('.fleet-type').on('click', function() {\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#type-select').text(jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).text());\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-option-box').css('display', 'none');\r\n let type = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).data('type');\r\n setFleetInfo(type);\r\n });\r\n //セレクトの値を一つ前に戻す\r\n //読込がまずったときに\r\n function setBackSelect() {\r\n console.log('setBackSelect');\r\n let options = jquery__WEBPACK_IMPORTED_MODULE_0___default()('.fleet-type');\r\n if(selected_type) {\r\n for (let option of options) {\r\n if(option.dataset.type === selected_type + '') { //文字列化してから比較\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#type-select').text(option.textContent);\r\n }\r\n }\r\n } else {\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#type-select').text('艦隊種別');\r\n localStorage.removeItem('selected_type');\r\n }\r\n }\r\n //計算結果から抜き出して変数セット\r\n //引数:艦隊種別\r\n function setFleetInfo(f) {\r\n console.log(`f : ${f}`);\r\n f--; //配列指定の為\r\n //初期化してから\r\n for (var key in com) {\r\n com[key] = 0;\r\n }\r\n try {\r\n if(f < 4) {\r\n //通常艦隊\r\n f_length = c_lengths[f];\r\n console.log(`f_length : ${f_length}`);\r\n if(!f_length) {\r\n alert('処理中断: 艦隊が空かも?');\r\n //空欄化\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').val('');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').blur();\r\n setBackSelect();\r\n return;\r\n }\r\n //構成艦のid\r\n f_ids = c_ids[f];\r\n console.log(`f_ids : ${f_ids}`);\r\n //構成艦の名前\r\n f_names = c_names[f];\r\n console.log(`f_names : ${f_names}`);\r\n let types = c_types[f];\r\n console.log(`types : ${types}`);\r\n //変数反映\r\n reflectionCom(types);\r\n //索敵値\r\n f_search = c_searchs[f];\r\n console.log(`f_search : ${f_search}`);\r\n //速度\r\n speed = c_speeds[f];\r\n console.log(`speed : ${speed}`);\r\n //ドラム缶、大発、電探搭載艦数カウント 変数にセット\r\n f_drum = c_drums[f];\r\n f_radar = c_radars[f];\r\n f_craft = c_crafts[f];\r\n f_kanko = c_kanko[f];\r\n console.log(`ドラム缶 : ${f_drum}`);\r\n console.log(`電探 : ${f_radar}`);\r\n console.log(`大発系 : ${f_craft}`);\r\n console.log(`寒甲 : ${f_kanko}`);\r\n if(f_length === 7) {\r\n f_united = '遊撃部隊';\r\n } else {\r\n f_united = '通常艦隊';\r\n }\r\n console.log(`f_united : ${f_united}`);\r\n } else {\r\n //連合艦隊\r\n //第一艦隊と第二艦隊を足したり\r\n f_length = c_lengths[0] + c_lengths[1];\r\n f2_length = c_lengths[1];\r\n console.log(`f_length : ${f_length}`);\r\n if(!c_lengths[0] || !c_lengths[1]) {\r\n alert('処理中断: 艦隊が空かも?');\r\n setBackSelect();\r\n //空欄化\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').val('');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').blur();\r\n return;\r\n }\r\n //構成艦のid\r\n f_ids = c_ids[0].concat(c_ids[1]);\r\n console.log(`f_ids : ${f_ids}`);\r\n //構成艦の名前\r\n f_names = c_names[0].concat(c_names[1]);\r\n f2_names = c_names[1];\r\n console.log(`f_names : ${f_names}`);\r\n let types = c_types[0].concat(c_types[1]);\r\n console.log(`types : ${types}`);\r\n //変数反映\r\n reflectionCom(types);\r\n //索敵値 各項足し合わせ\r\n f_search = [];\r\n for (var i = 0; i < 4; i++) {\r\n f_search.push(new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](c_searchs[0][i]).plus(new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](c_searchs[1][i])));\r\n }\r\n console.log(`f_search : ${f_search}`);\r\n //速度\r\n //低い方から適用\r\n if(c_speeds[0] === '低速艦隊' || c_speeds[1] === '低速艦隊') {\r\n speed = '低速艦隊';\r\n } else if(c_speeds[0] === '高速艦隊' || c_speeds[1] === '高速艦隊') {\r\n speed = '高速艦隊';\r\n } else if(c_speeds[0] === '高速艦隊+' || c_speeds[1] === '高速艦隊+') {\r\n speed = '高速艦隊+';\r\n } else {\r\n speed = '最速艦隊';\r\n }\r\n console.log(`speed : ${speed}`);\r\n //ドラム缶、大発、電探搭載艦数カウント 変数にセット\r\n f_drum = c_drums[0] + c_drums[1];\r\n f_radar = c_radars[0] + c_radars[1];\r\n f_craft = c_crafts[0] + c_crafts[1];\r\n f_kanko = c_kanko[0] + c_kanko[1];\r\n console.log(`ドラム缶 : ${f_drum}`);\r\n console.log(`電探 : ${f_radar}`);\r\n console.log(`大発系 : ${f_craft}`);\r\n //艦隊種別\r\n if(f === 4) {\r\n f_united = '空母機動部隊';\r\n } else if(f === 5) {\r\n f_united = '水上打撃部隊';\r\n } else if(f === 6) {\r\n f_united = '輸送護衛部隊';\r\n }\r\n console.log(`f_united : ${f_united}`);\r\n }\r\n } catch(e) {\r\n console.log(`error : ${e}`);\r\n alert('処理中断: 艦隊情報の取得に失敗しました');\r\n //空欄化\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').val('');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').blur();\r\n setBackSelect();\r\n return;\r\n }\r\n //気休めだけども保存前にチェック\r\n if(f_length && f_ids && f_names && f_search && f_search[0] && speed) {\r\n //丸ごとlocalstorageへ\r\n localStorage.setItem('fleet', JSON.stringify(i_json));\r\n f_flag = true;\r\n selected_type = f + 1; //配列司偵の為に引いた分足しなおす\r\n localStorage.setItem('selected_type', selected_type);\r\n //表示\r\n reloadImportDisplay();\r\n startSim();\r\n } else {\r\n alert('処理中断: 入力値に不備があるかも?');\r\n //空欄化\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').val('');\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#fleet-import').blur();\r\n setBackSelect();\r\n }\r\n }\r\n // cシリーズ初期化\r\n function inCs() {\r\n c_lengths = [];\r\n c_ids = [];\r\n c_names = [];\r\n c_types = [];\r\n c_searchs = [];\r\n c_speeds = [];\r\n c_drums = [];\r\n c_radars = [];\r\n c_crafts = [];\r\n c_kanko = [];\r\n }\r\n //ドラム缶、大発、電探搭載艦数, 寒甲カウント\r\n function countUnits(num) {\r\n //先ず初期化\r\n let drum = 0;\r\n let radar = 0;\r\n let craft = 0;\r\n let kanko = 0;\r\n for(let i = 0;i < c_lengths[num - 1];i++) {\r\n let e_ids = getEqIds(c_ids[num - 1][i], num);\r\n //一隻につき1回だけカウント\r\n let d = true;\r\n let r = true;\r\n let c = true;\r\n let k = true;\r\n for(let e_id of e_ids) {\r\n if(e_id === 75) { //ドラム缶\r\n if(d) {\r\n drum++;\r\n d = false;\r\n }\r\n }\r\n //typeを取得\r\n let t_id = getEqType(e_id);\r\n if(t_id === 5812 || t_id === 5813) {\r\n if(r) {\r\n //小型電探\r\n //大型電探\r\n radar++;\r\n r = false;\r\n }\r\n } else if(t_id === 81424 || t_id === 84724|| t_id === 203746) {\r\n //特大発動艇+戦車第11連隊及びM4A1のみ除外 M4A1はtype:84524で含まれない\r\n if(e_id !== 230) {//特大発動艇+戦車第11連隊及びM4A1のみ除外 M4A1はtype:84524で含まれない\r\n if(c) {\r\n craft++;\r\n c = false;\r\n }\r\n }\r\n } else if(e_id === 402) { //寒甲\r\n if(k) {\r\n kanko++;\r\n k = false;\r\n }\r\n }\r\n }\r\n }\r\n c_drums.push(drum);\r\n c_radars.push(radar);\r\n c_crafts.push(craft);\r\n c_kanko.push(kanko);\r\n }\r\n //typeの先頭3つを連結してidとして返す(数値型)\r\n function getEqType(e_id) {\r\n let entry = e_data.find(entry => entry.id === e_id);\r\n return Number(entry.type.slice(0, 3).join(''));\r\n }\r\n //速度を取得 高速+艦隊etc\r\n function calcSpeed(num) {\r\n let arr = [];\r\n for(let i = 0;i < c_lengths[num - 1];i++) {\r\n let e_ids = getEqIds(c_ids[num - 1][i], num);\r\n let rf = getEqRfs(c_ids[num - 1][i], num);\r\n /*\r\n 33:タービン\r\n 34:強化缶\r\n 87:新型缶\r\n */\r\n let tur = 0; //タービン\r\n let kan = 0; //強化缶\r\n let n_kan = 0; //新型缶\r\n let pow = 0; //新型缶☆7↑\r\n console.log(`e_ids : ${e_ids}`);\r\n for(let q = 0;q < e_ids.length;q++) {\r\n if(e_ids[q] === 33) {\r\n tur++;\r\n } else if(e_ids[q] === 34) {\r\n kan++;\r\n } else if(e_ids[q] === 87) {\r\n n_kan++;\r\n if(rf[q] > 6) {\r\n pow++;\r\n }\r\n }\r\n }\r\n let kans = kan + n_kan;\r\n let ship = s_data.find(entry => entry.id === c_ids[num - 1][i]);\r\n let sg = ship.sg;\r\n let val = 0;\r\n console.log(`sg : ${sg}`);\r\n console.log(`tur : ${tur}, n_kan : ${n_kan}, pow : ${pow}`);\r\n switch(sg) { //thanks to Aerial Combat Simulator 無駄がなく美しい\r\n case 0: //高速A\r\n val = 1;\r\n if(tur && n_kan || pow > 1) {\r\n val = 3;\r\n } else if(tur && kans || pow) {\r\n val = 2;\r\n }\r\n arr.push(val);\r\n break;\r\n case 1: //高速B1\r\n val = 1;\r\n if(tur && n_kan && kans > 1) {\r\n val = 3;\r\n } else if(tur && kans) {\r\n val = 2;\r\n }\r\n arr.push(val);\r\n break;\r\n case 2://高速B2\r\n val = 1;\r\n if(tur &&(n_kan > 1 || kans > 2)) {\r\n val = 3;\r\n } else if(tur && kans) {\r\n val = 2;\r\n }\r\n arr.push(val);\r\n break;\r\n case 3: //高速C\r\n val = 1;\r\n if(tur && kans) {\r\n val = 2;\r\n }\r\n arr.push(val);\r\n break;\r\n case 4: //低速A群\r\n val = 0;\r\n if(tur && n_kan && kans > 2) {\r\n val = 3;\r\n } else if(tur && pow > 1) {\r\n val = 3;\r\n } else if(tur && n_kan && kans > 1) {\r\n val = 2;\r\n } else if(tur && pow) {\r\n val = 2;\r\n } else if(tur && kans) {\r\n val = 1;\r\n }\r\n arr.push(val);\r\n break;\r\n case 5: //低速B\r\n val = 0;\r\n if(tur && (n_kan > 1 || kans > 2)) {\r\n val = 2;\r\n } else if(tur && kans) {\r\n val = 1;\r\n }\r\n arr.push(val);\r\n break;\r\n case 6: //低速C\r\n val = 0;\r\n if(tur && kans) {\r\n val = 1;\r\n }\r\n arr.push(val);\r\n break;\r\n case 7: //低速D\r\n val = 0;\r\n if(tur && n_kan) {\r\n val = 2;\r\n } else if(n_kan || tur && kans) {\r\n val = 1;\r\n }\r\n arr.push(val);\r\n break;\r\n case 8: //低速E\r\n val = 0;\r\n if(tur && n_kan && kans > 1) {\r\n val = 3;\r\n } else if(tur && n_kan) {\r\n val = 2;\r\n } else if(tur && kans) {\r\n val = 1;\r\n } else if(n_kan) {\r\n val = 1;\r\n }\r\n arr.push(val);\r\n break;\r\n case 9: //サミュ/改&夕張改二特\r\n val = 0;\r\n if(tur && (n_kan > 1 || kans > 2)) {\r\n val = 2;\r\n } else if(tur) {\r\n val = 1;\r\n }\r\n arr.push(val);\r\n break;\r\n }\r\n }\r\n console.log(`艦隊各速度 : ${arr}`);\r\n let res = '';\r\n if(arr.every(elem => elem === 3)) {\r\n res = '最速艦隊';\r\n } else if(arr.every(elem => elem > 1)) {\r\n res = '高速+艦隊';\r\n } else if(arr.every(elem => elem > 0)) {\r\n res = '高速艦隊';\r\n } else {\r\n res = '低速艦隊';\r\n }\r\n return res;\r\n }\r\n //構成艦のidを取得 配列で返す\r\n function getIdsFromFleet(num) {\r\n const ids = [];\r\n const f = `f${num}`;\r\n for (let i = 1; i <= c_lengths[num - 1]; i++) {\r\n const key = \"s\" + i;\r\n if (i_json[f][key] && i_json[f][key].hasOwnProperty(\"id\")) {\r\n ids.push('' + i_json[f][key].id); //文字列化\r\n }\r\n }\r\n return ids;\r\n }\r\n //構成艦数カウント\r\n function countShips(num) {\r\n // f1内のsキーの配下にあるオブジェクト数をカウント\r\n try {\r\n const count = Object.keys(i_json[`f${num}`]).filter(key => /^s\\d+$/.test(key)).length;\r\n return count;\r\n } catch(e) {\r\n console.log('多分艦隊が空');\r\n return 0;\r\n }\r\n }\r\n //索敵計算\r\n function calcSeek(num) {\r\n let res = [];\r\n let sum_base = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](0); //艦娘索敵値によるスコア\r\n let f_length_correct = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](2 * (6 - c_lengths[num - 1])); //隻数補正\r\n let sum_eq = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](0); //装備によるスコア\r\n let command = 120;\r\n if(i_json.hqlv) { //オリジナルのデッキビルダーには司令レベルが無いみたい\r\n command = i_json.hqlv;\r\n }\r\n command = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](command).times(0.4); //司令部補正\r\n for (let i = 0; i < c_lengths[num - 1]; i++) {\r\n //素の索敵値計算\r\n const key = 's' + (i + 1);\r\n let lv = i_json[`f${num}`][key]['lv'];\r\n //索敵値の最大値と最小値を取得\r\n let ship = s_data.find(entry => entry.id === c_ids[num - 1][i]);\r\n let min_seek = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](ship.seek);\r\n let max_seek = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](ship.max_seek);\r\n let cur_seek = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](max_seek).minus(min_seek).times(lv).div(99).floor().plus(min_seek);\r\n console.log(`艦名 : ${c_names[num - 1][i]}, 素索敵値 : ${cur_seek}`);\r\n //装備id取得\r\n let i_ids = getEqIds(c_ids[num - 1][i], num);\r\n console.log(`装備id : ${i_ids}`);\r\n //装備ボーナス\r\n let bonus = getSeekBonus(ship, i_ids, num);\r\n console.log(`seek_bonus : ${bonus}`);\r\n //素の索敵値の平方根を加算\r\n sum_base = sum_base.plus(decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"].sqrt(cur_seek.plus(bonus)));\r\n //改修値取得\r\n let rfs = getEqRfs(c_ids[num - 1][i], num);\r\n for(let q = 0;q < i_ids.length;q++) {\r\n //装備の索敵値が1以上だったらあれこれ\r\n let eq = e_data.find(entry => entry.id === i_ids[q]);\r\n let seek = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](eq.seek);\r\n if(seek > 0) {\r\n //係数\r\n let coefficient = getEqCo(i_ids[q]);\r\n let eq_co = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](coefficient[0]); //装備係数\r\n let rf_co = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](coefficient[1]); //改修係数\r\n let rf = new decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](rfs[q]);\r\n console.log(`装備係数 : ${coefficient[0]}, 改修係数 : ${coefficient[1]}`);\r\n sum_eq = sum_eq.plus(eq_co.times(seek.plus(rf_co.times(decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"].sqrt(rf)))));\r\n }\r\n }\r\n }\r\n let material = sum_base.plus(f_length_correct).minus(command);\r\n //係数 四捨五入で小数第二位まで\r\n res.push((material.plus(sum_eq)).toDecimalPlaces(2, decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"].ROUND_DOWN));\r\n res.push((material.plus(sum_eq.times(2))).toDecimalPlaces(2, decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"].ROUND_DOWN));\r\n res.push((material.plus(sum_eq.times(3))).toDecimalPlaces(2, decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"].ROUND_DOWN));\r\n res.push((material.plus(sum_eq.times(4))).toDecimalPlaces(2, decimal_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"].ROUND_DOWN));\r\n return res;\r\n }\r\n //装備ボーナス取得 艦のjson, 装備id(配列)\r\n function getSeekBonus(ship, e_ids, num) {\r\n console.log(ship);\r\n let res = 0;\r\n let id = ship.id;\r\n let name = ship.name;\r\n let na = ship.na;\r\n let type = ship.type;\r\n let dup = []; // 重複不可のがきたらこれに追加\r\n let e_length = e_ids.length;\r\n for(let i = 0;i < e_length;i++) {\r\n let e_id = e_ids[i];\r\n let eq = e_data.find(entry => entry.id === e_id);\r\n switch(e_id) {\r\n case 315: //SG初期\r\n if(name === '丹陽' || name === '雪風改二') {\r\n if(!dup.includes(e_id)) {\r\n res += 3;\r\n dup.push(e_id);\r\n }\r\n } else if(na === 1) {\r\n res += 4;\r\n }\r\n break;\r\n case 456: //SG後期\r\n if(name === '丹陽' || name === '雪風改二') {\r\n if(!dup.includes(e_id)) {\r\n res += 3;\r\n dup.push(e_id);\r\n }\r\n } else if(na === 1) {\r\n res += 4;\r\n } else if(na === 3) {\r\n res += 2;\r\n }\r\n break;\r\n case 278: // SK\r\n if(na === 1) {\r\n if(!dup.includes(e_id)) {\r\n res += 1;\r\n dup.push(e_id);\r\n }\r\n }\r\n break;\r\n case 279: //SK+SG\r\n if(na === 1) {\r\n if(!dup.includes(e_id)) {\r\n res += 2;\r\n dup.push(e_id);\r\n }\r\n } else if(na === 3) {\r\n if(!dup.includes(e_id)) {\r\n res += 1;\r\n dup.push(e_id);\r\n }\r\n }\r\n break;\r\n case 517: // 清霜逆探\r\n var gifted = ['朝霜改二','清霜改二','初霜改二','潮改二','Верный','霞改二','時雨改三','雪風改二'];\r\n if(name === '清霜改二丁') {\r\n if(!dup.includes(e_id)) {\r\n res += 3;\r\n dup.push(e_id);\r\n }\r\n } else if(gifted.includes(name)) {\r\n if(!dup.includes(e_id)) {\r\n res += 2;\r\n dup.push(e_id);\r\n }\r\n } else if(na === 0 && type === '駆逐艦') {\r\n if(!dup.includes(e_id)) {\r\n res += 1;\r\n dup.push(e_id);\r\n }\r\n }\r\n break;\r\n case 30: // 21号対空電探\r\n case 410: // 21号対空電探改二\r\n let akizuki = ['秋月','照月','初月','涼月','冬月'];\r\n let mogami = ['最上改','最上改二','最上改二特'];\r\n if(akizuki.some(item => item.includes(name)) || mogami.includes(name)) {\r\n if(!dup.includes(e_id)) {\r\n res += 2;\r\n dup.push(e_id);\r\n }\r\n }\r\n break;\r\n case 118: // 紫雲\r\n if(name.includes('大淀')) {\r\n res += 2;\r\n let rf = getEqRfs(id, num)[i];\r\n if(rf === 10) { // 改修maxで更に+1\r\n res += 1;\r\n }\r\n }\r\n break;\r\n case 414: // SOC seagull\r\n if(na === 1) {\r\n if(type === '軽巡洋艦' || type === '重巡洋艦') {\r\n let rf = getEqRfs(id, num)[i];\r\n if(!dup.includes(e_id)) {\r\n res += 2;\r\n //改修でさらにボーナス\r\n if(rf > 3) {\r\n res += 1;\r\n }\r\n dup.push(e_id);\r\n }\r\n } else if(type === '戦艦' || type === '巡洋戦艦') {\r\n if(!dup.includes(e_id)) {\r\n res += 1;\r\n dup.push(e_id);\r\n }\r\n }\r\n }\r\n break;\r\n case 115: // Ar196改\r\n if(name.includes('Bismarck') || name.includes('Prinz Eugen')) {\r\n res += 2;\r\n }\r\n break;\r\n case 371: //Fairey Seafox改\r\n if(name.includes('Gotland')) {\r\n if(!dup.includes(e_id)) {\r\n res += 6;\r\n dup.push(e_id);\r\n }\r\n } else if(name.includes('Nelson')) {\r\n if(!dup.includes(e_id)) {\r\n res += 5;\r\n dup.push(e_id);\r\n } \r\n } else if(name.includes('Commandant Teste')) {\r\n if(!dup.includes(e_id)) {\r\n res += 4;\r\n dup.push(e_id);\r\n }\r\n } else if(name.includes('Warspite') || name.includes('Richelieu') || name.includes('Jean Bart')) {\r\n if(!dup.includes(e_id)) {\r\n res += 3;\r\n dup.push(e_id);\r\n }\r\n }\r\n break;\r\n case 370: //Swordfish Mk.II改(水偵型)\r\n if(name.includes('Warspite')) {\r\n if(!dup.includes(e_id)) {\r\n res += 3;\r\n dup.push(e_id);\r\n }\r\n } else if(name.includes('Nelson') || name.includes('Sheffield') || name.includes('Gotland')) {\r\n if(!dup.includes(e_id)) {\r\n res += 2;\r\n dup.push(e_id);\r\n }\r\n } else if(name.includes('Commandant Teste') || name.includes('瑞穂') || name.includes('神威')) {\r\n if(!dup.includes(e_id)) {\r\n res += 1;\r\n dup.push(e_id);\r\n }\r\n }\r\n break;\r\n case 194: //Laté 298B\r\n var gifted = ['Commandant Teste','Richelieu','Jean Bart','瑞穂','神威'];\r\n if(gifted.some(item => item.includes(name))) {\r\n res += 2;\r\n dup.push(e_id);\r\n }\r\n break;\r\n case 415: //SO3C Seamew改\r\n if(na === 1) {\r\n if(type === '軽巡洋艦' || type === '重巡洋艦') {\r\n if(!dup.includes(e_id)) {\r\n res += 2;\r\n dup.push(e_id);\r\n }\r\n } else if(type === '戦艦' || type === '巡洋戦艦') {\r\n if(!dup.includes(e_id)) {\r\n res += 1;\r\n dup.push(e_id);\r\n }\r\n }\r\n }\r\n break;\r\n case 369: //Swordfish Mk.III改(水上機型/熟練)\r\n if(name === 'Gotland andra') {\r\n if(dup.filter(item => item === e_id).length === 0) {\r\n res += 4;\r\n dup.push(e_id);\r\n } else if(dup.filter(item => item === e_id).length === 1) {\r\n res += 1;\r\n dup.push(e_id);\r\n }\r\n } else if(name.includes('Gotland') || name.includes('Commandant Teste')) {\r\n if(!dup.includes(e_id)) {\r\n res += 3;\r\n dup.push(e_id);\r\n }\r\n } else if(name.includes('瑞穂') || name.includes('神威')) {\r\n if(!dup.includes(e_id)) {\r\n res += 2;\r\n dup.push(e_id);\r\n }\r\n }\r\n break;\r\n case 368: //Swordfish Mk.III改(水上機型)\r\n if(name === 'Gotland andra') {\r\n if(dup.filter(item => item === e_id).length === 0) {\r\n res += 4;\r\n dup.push(e_id);\r\n } else if(dup.filter(item => item === e_id).length < 5) {\r\n res += 3;\r\n dup.push(e_id);\r\n }\r\n } else if(name.includes('Gotland')) {\r\n res += 3;\r\n } else if(name.includes('Commandant Teste') || name.includes('瑞穂') || name.includes('神威')) {\r\n res += 2;\r\n }\r\n break;\r\n case 367: //Swordfish(水上機型)\r\n if(name.includes('Gotland') || name.includes('Commandant Teste') || name.includes('瑞穂') || name.includes('神威')) {\r\n res += 1;\r\n }\r\n break;\r\n case 408: //装甲艇(AB艇)\r\n if(name.includes('神州丸')) {\r\n res += 2;\r\n } else if(name.includes('あきつ丸') || type === '駆逐艦') {//本来大発の乗る駆逐艦だが、駆逐に乗ってる時点でボーナスつけちゃう\r\n res += 1;\r\n }\r\n break;\r\n case 409: //武装大発\r\n if(name.includes('神州丸')) {\r\n res += 2;\r\n } else if(name.includes('あきつ丸')) {//本来大発の乗る駆逐艦だが、駆逐に乗ってる時点でボーナスつけちゃう\r\n res += 1;\r\n }\r\n break;\r\n case 412: //熟練見張員\r\n if(na === 0) {\r\n if(type === '駆逐艦') {\r\n res += 1;\r\n } else if(type='軽巡洋艦') {\r\n res += 3;\r\n } else if(type === '重巡洋艦') {\r\n res += 1;\r\n }\r\n }\r\n break;\r\n case 129: //見張員\r\n if(na === 0) {\r\n if(type === '駆逐艦') {\r\n res += 1;\r\n } else if(type='軽巡洋艦') {\r\n res += 3;\r\n } else if(type === '重巡洋艦') {\r\n res += 3;\r\n }\r\n }\r\n break;\r\n case 521: //紫雲(熟練)\r\n if(name.includes('大淀改')) {\r\n let rf = getEqRfs(id, num)[i];\r\n if(rf > 0) { // 改修1以上で+5\r\n res += 5;\r\n }\r\n if(rf > 3) { //☆4以上で更に+1\r\n res += 1;\r\n }\r\n } else if(name.includes('三隈改二特')) {\r\n let rf = getEqRfs(id, num)[i];\r\n if(rf > 0) { // 改修1以上で+4\r\n res += 4;\r\n }\r\n }\r\n break;\r\n case 522: //零式小型水上機\r\n if(type === '潜水艦' || type === '潜水空母') {\r\n res += 3;\r\n }\r\n break;\r\n case 523: //零式小型水上機(熟練)\r\n if(type === '潜水艦' || type === '潜水空母') {\r\n res += 4;\r\n }\r\n break;\r\n }\r\n }\r\n return res;\r\n }\r\n //装備係数&改修係数取得 配列[装備係数, 改修係数]を返す\r\n function getEqCo(id) {\r\n let res = [];\r\n //typeを取得\r\n let e_id = getEqType(id);\r\n //やや無駄になるが2回に分けた方が見やすくて良いと思う\r\n switch(e_id) {\r\n //装備係数\r\n case 356: //艦戦\r\n case 357: //艦爆\r\n case 53645: //水戦\r\n case 173341: //大型飛行艇\r\n case 31626: //対潜哨戒機\r\n case 31525: //回転翼機\r\n case 34425: //S51J & S51J改\r\n case 34057: //噴式戦闘爆撃機\r\n case 111: //小口径主砲\r\n case 112: //中口径主砲\r\n case 5812: //小型電探\r\n case 5813: //大型電探\r\n case 244251: //潜水電探\r\n case 2332: //潜水魚雷\r\n case 71014: //ソナー\r\n case 71040: //大型ソナー\r\n case 81829: //探照灯\r\n case 81842: //大型探照灯\r\n case 132335: //航空要員\r\n case 162739: //見張員\r\n case 122234: //司令部\r\n case 2422: //甲標的\r\n case 84724: //AB艇\r\n res.push(0.6);\r\n break;\r\n case 358: //艦攻\r\n res.push(0.8);\r\n break;\r\n case 579: //艦偵\r\n res.push(1);\r\n break;\r\n case 54311: //水爆\r\n res.push(1.1);\r\n break;\r\n case 5710: //水偵\r\n res.push(1.2);\r\n break;\r\n }\r\n switch(e_id) {\r\n //改修係数\r\n case 31525: //回転翼機\r\n case 34425: //S51J & S51J改\r\n case 162739: //見張員\r\n res.push(0);\r\n break;\r\n case 54311: //水爆\r\n res.push(1.15);\r\n break;\r\n case 579: //艦偵\r\n case 173341: //大型飛行艇\r\n case 5710: //水偵\r\n res.push(1.2);\r\n break;\r\n case 5812: //小型電探\r\n res.push(1.25);\r\n break;\r\n case 5813: //大型電探\r\n res.push(1.4);\r\n break;\r\n default:\r\n res.push(0);\r\n break;\r\n }\r\n return res;\r\n }\r\n //艦idと艦隊番号から装備idを配列で得る\r\n function getEqIds(s_id, num) {\r\n const ids = [];\r\n for (const s_key in i_json[`f${num}`]) {\r\n let ship = i_json[`f${num}`][s_key];\r\n if (Number(ship.id) && Number(ship.id) === Number(s_id)) { //本家デッキビルダーへの対応で艦IDは数値化\r\n let items = ship.items;\r\n for(const i_key in items) {\r\n if(items[i_key].id) {\r\n ids.push(items[i_key].id);\r\n }\r\n }\r\n }\r\n }\r\n return ids;\r\n }\r\n //艦idから装備改修値を配列で得る\r\n function getEqRfs(s_id, num) {\r\n const rfs = [];\r\n for (const s_key in i_json[`f${num}`]) {\r\n let ship = i_json[`f${num}`][s_key];\r\n if (Number(ship.id) && Number(ship.id) === Number(s_id)) { //本家デッキビルダーへの対応で艦IDは数値化\r\n let items = ship.items;\r\n for(const i_key in items) {\r\n if(items[i_key].rf) {\r\n rfs.push(items[i_key].rf);\r\n } else { //デッキビルダー本家は改修値ゼロはキーがない\r\n rfs.push(0);\r\n }\r\n }\r\n }\r\n }\r\n return rfs;\r\n }\r\n //艦種を変数に反映\r\n function reflectionCom(types) {\r\n let res = [];\r\n for(let i = 0;i < types.length;i++) {\r\n switch(types[i]) {\r\n case '戦艦':\r\n case '巡洋戦艦':\r\n com['BB']++;\r\n break;\r\n case '航空戦艦':\r\n com['BBV']++;\r\n break;\r\n case '正規空母':\r\n com['CV']++;\r\n break;\r\n case '装甲空母':\r\n com['CVB']++;\r\n break;\r\n case '軽空母':\r\n com['CVL']++;\r\n break;\r\n case '重巡洋艦':\r\n com['CA']++;\r\n break;\r\n case '航空巡洋艦':\r\n com['CAV']++;\r\n break;\r\n case '軽巡洋艦':\r\n com['CL']++;\r\n break;\r\n case '重雷装巡洋艦':\r\n com['CLT']++;\r\n break;\r\n case '練習巡洋艦':\r\n com['CT']++;\r\n break;\r\n case '駆逐艦':\r\n com['DD']++;\r\n break;\r\n case '海防艦':\r\n com['DE']++;\r\n break;\r\n case '潜水艦':\r\n com['SS']++;\r\n break;\r\n case '潜水空母':\r\n com['SSV']++;\r\n break;\r\n case '水上機母艦':\r\n com['AV']++;\r\n break;\r\n case '補給艦':\r\n com['AO']++;\r\n break;\r\n case '揚陸艦':\r\n com['LHA']++;\r\n break;\r\n case '潜水母艦':\r\n com['AS']++;\r\n break;\r\n case '工作艦':\r\n com['AR']++;\r\n break;\r\n }\r\n }\r\n }\r\n //構成艦の名前を配列で返す\r\n //引数:随伴であるか否か\r\n function getShipName(num) {\r\n let names = [];\r\n for (let id of c_ids[num - 1]) {\r\n let ship = s_data.find((item) => item.id === id);\r\n if (ship) {\r\n names.push(ship.name);\r\n }\r\n }\r\n return names;\r\n }\r\n //idから艦種取得 配列で渡す\r\n function getType(num) {\r\n let types = [];\r\n for (let id of c_ids[num - 1]) {\r\n let entry = s_data.find(entry => entry.id === id);\r\n if (entry) {\r\n types.push(entry.type);\r\n }\r\n }\r\n return types;\r\n }\r\n //艦隊情報表示\r\n function reloadImportDisplay() {\r\n jquery__WEBPACK_IMPORTED_MODULE_0___default()('#import-display').empty();\r\n let part = '';\r\n if(f_united && f_united !== '遊撃部隊' && f_united !== '通常艦隊') {\r\n //連合艦隊\r\n part += `主力: ${f_names[0]}`;\r\n for(let i = 1;i < f_length - f2_length;i++) {\r\n part += ` | ${f_names[i]}`;\r\n }\r\n part += ` 随伴: ${f2_names[0]}`;\r\n for(let i = 1;i < f2_length;i++) {\r\n part += ` | ${f2_names[i]}`;\r\n }\r\n } else {\r\n //通常艦隊\r\n part += `${f_names[0]}`;\r\n for(let i = 1;i < f_length;i++) {\r\n part += ` | ${f_names[i]}`;\r\n }\r\n }\r\n let u = '';\r\n if(f_united !== '通常艦隊') {\r\n u += `